PHP 8.4.1 Released!

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

callback 函数接受一个参数;返回用户输入。

返回值

成功时返回 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 note

up
1
thflori
6 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;
}
To Top