The original STDIN, STDOUT and STDERR are system constants in PHP. They are populated with the file descriptor resources of the standard input, output and error upon initialization of PHP.
The php.net documentation describes the following regarding resources in constants:
The value of the constant; only scalar and null values are allowed.
Scalar values are integer, float, string or boolean values. It is
possible to define resource constants, however it is not recommended
and may cause unpredictable behavior.
When fclose(STDOUT)
is called, the file descriptor resource is closed and detached from the STDOUT constant. Contrary to the default behavior of constants, the STDOUT constant is changed.
When a string is echo'ed like echo "Hello, World!"
, PHP will not use the STDOUT constant, but it will query the current "standard out" file descriptor in real-time from the operating system. Moreover, the STDOUT constant itself is rendered unusable once it is fclose'd. Even a statement like fwrite(STDOUT, "hello")
will not work.
When a new file descriptor is configured for the standard output, this new file descriptor is conveniently put in $STDOUT
. Note that this is a variable and not a constant. It is by definition not possible to redefine a constant in PHP, and the system constant STDOUT is no exception here. There is currently no way to reassign the new file descriptor to the STDOUT constant.
Ultimately, to make this work more intuitively, the PHP team should consider making convenience functions to reassign these file descriptors or at least make the system constants operate more like "magic constants" in a sense that they auto evaluate to the actual file descriptors.