函式名稱:parallel\Events\Input::add()
適用版本:parallel 1.1.0 或更高版本
函式用法: parallel\Events\Input::add()函式用於將一個檔案描述符或資源新增到事件迴圈中,以便在該描述符上監聽可讀事件。
語法:
public void parallel\Events\Input::add(int $fd, callable $callback)
引數:
- $fd: 表示要監聽的檔案描述符或資源,可以是一個整數或一個資源。
- $callback: 當檔案描述符上有可讀事件時,將被呼叫的回撥函式。
返回值: 該函式沒有返回值。
示例:
$input = fopen('input.txt', 'r');
$eventLoop = new parallel\Events\EventLoop();
$inputHandler = function($input) {
$data = fread($input, 1024);
echo "Received data: " . $data . "\n";
};
$eventLoop->add($input, $inputHandler);
$eventLoop->run();
在上面的示例中,我們首先開啟了一個名為input.txt的文字檔案,並將其用於建立一個檔案描述符$input。然後,我們建立了一個parallel\Events\EventLoop物件$eventLoop用於管理事件迴圈。接下來,我們定義了一個名為$inputHandler的回撥函式,用於處理可讀事件。最後,我們透過呼叫$eventLoop的add()方法將$input和$inputHandler新增到事件迴圈中。最後一行程式碼$eventLoop->run()會啟動事件迴圈,使其開始監聽$input上的可讀事件。當$input上有資料可讀時,$inputHandler將被呼叫,並列印出接收到的資料。