PHP 循环监听用户输入 [英] PHP loop listen for user input

查看:38
本文介绍了PHP 循环监听用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在控制台上运行的 PHP 脚本.

I have a PHP script that run on console.

while(1) {
 doStuff();
 sleep(2);
}

我需要接受来自控制台的输入.我不想每次都停止循环并等待我输入一些文本.

I need to accept input from the console. I don't want loop stop each time and wait for me to input some text.

我想要的是 while 循环继续正常运行,如果我在控制台中输入内容,php 脚本能够读取该文本并更新一些变量.

What i want is while loop continue as normal, if i type something in console, php script able to read that text and update some variable.

这能做到吗?

推荐答案

您可以使用非阻塞 I/O 来做到这一点.您将需要 stream_set_blocking 方法和 stream_select:

You can do this with non-blocking I/O. You'll need the stream_set_blocking method and stream_select:

stream_set_blocking(STDIN, FALSE);

while (1) {
    doStuff();

    $readStreams = [STDIN];
    $timeout = 2;

    // stream_select will block for $timeout seconds OR until STDIN
    // contains some data to read.
    $numberOfStreamsWithData = stream_select(
        $readStreams,
        $writeStreams = [],
        $except = [],
        $timeout
    );

    if ($numberOfStreamsWithData > 0) {
        $userInput = fgets(STDIN);

        // process $userInput as you see fit
    } else {
        // no user input; repeat loop as normal
    }
}

这篇关于PHP 循环监听用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆