readline_callback_handler_install
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
readline_callback_handler_install — 初始化一个 readline 回调接口,然后终端输出提示信息并立即返回
说明
设置一个 readline 回调接口然后输出 prompt
并立即返回.
第二次调用这个函数不需要移除上一个回调接口,这个函数将自动覆盖旧的接口.
当配合 stream_select() 时回调的特性非常有用,它允许在 IO 与用户输入 间交叉进行,不像readline().
参数
-
prompt
-
提示信息.
-
callback
-
callback
函数需要一个参数; 用户输入将被返回.
返回值
成功时返回 true
, 或者在失败时返回 false
。
范例
示例 #1 Readline Callback Interface Example
<?php
function rl_callback($ret)
{
global $c, $prompting;
echo "You entered: $ret\n";
$c++;
if ($c > 10) {
$prompting = false;
readline_callback_handler_remove();
} else {
readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');
}
}
$c = 1;
$prompting = true;
readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');
while ($prompting) {
$w = NULL;
$e = NULL;
$n = stream_select($r = array(STDIN), $w, $e, null);
if ($n && in_array(STDIN, $r)) {
// read a character, will call the callback when a newline is entered
readline_callback_read_char();
}
}
echo "Prompting disabled. All done.\n";
?>
参见
- readline_callback_handler_remove() - 移除上一个安装的回调函数句柄并且恢复终端设置
- readline_callback_read_char() - 当一个行被接收时读取一个字符并且通知 readline 调用回调函数
- stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds

User Contributed Notes 1 note
thflori ¶
3 years ago
To read byte wise and multi line you can check the line_buffer from readline_info:
<?php
function read(int $count, string $prompt = null): string
{
$previous = '';
readline_callback_handler_install($prompt ?? " \e[D", function ($str) use (&$previous) {
$previous .= $str . PHP_EOL;
});
do {
$r = array(STDIN);
$n = stream_select($r, $w, $e, null);
if ($n && in_array(STDIN, $r)) {
readline_callback_read_char();
$str = $previous . readline_info('line_buffer');
}
} while (mb_strlen($str) < $count); // use strlen if you need the exact byte count
readline_callback_handler_remove();
return $str;
}
备份地址:http://www.lvesu.com/blog/php/function.readline-callback-handler-install.php