readline_callback_handler_install

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

readline_callback_handler_install初始化 readline 回调接口和终端,打印提示并立即返回

说明

readline_callback_handler_install(string $prompt, callable $callback): bool

设置 readline 回调接口,然后打印 prompt 并立即返回。在没有移除之前回调接口的情况下,调用此函数两次将自动并方便地覆盖旧的接口。

回调功能与 stream_select() 结合使用时非常有用,因为它允许交错 IO 和用户输入,这与 readline() 不同。

参数

prompt

提示消息。

callback

The callback function takes one parameter; the user input returned.

返回值

成功时返回 true,失败时返回 false

范例

范例 #1 Readline 回调接口示例

<?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";
?>

参见

添加笔记

用户贡献笔记 1 笔记

thflori
5 年前
要逐字节读取多行,您可以检查 readline_info 中的 line_buffer

<?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;
}
To Top