Input/output streams

The CLI SAPI defines a few constants for I/O streams to make programming for the command line a bit easier.

CLI 专用常量
常量名称 描述
STDIN

An already opened stream to stdin. This saves opening it with

<?php
$stdin 
fopen('php://stdin''r');
?>
If you want to read single line from stdin, you can use
<?php
$line 
trim(fgets(STDIN)); // reads one line from STDIN
fscanf(STDIN"%d\n"$number); // reads number from STDIN
?>

STDOUT

An already opened stream to stdout. This saves opening it with

<?php
$stdout 
fopen('php://stdout''w');
?>

STDERR

An already opened stream to stderr. This saves opening it with

<?php
$stderr 
fopen('php://stderr''w');
?>

有了以上常量,就无需自己建立指向诸如 stderr 的流,只需简单的使用这些常量来代替流指向:

php -r 'fwrite(STDERR, "stderr\n");'
无需自己来关闭这些流,PHP 会在脚本结束时自动完成这些操作。

注意:

These constants are not available if reading the PHP script from stdin.