PHP 8.5: Returning non-string values from a user output handler is deprecated
PHP provides a series of ob_*
functions that allow running nested output buffers, explicitly flushing the buffer, and setting a custom output buffer handler.
When a custom output buffer handler is set, that function will be can further process the buffer contents, or pass the buffer contents elsewhere. For example, a custom output buffer handler can rewrite the contents written by print
calls, compress them, write them to a file, and so on.
Output buffering is a feature that existed in PHP for a long time, and predates strict and scalar types. Return values of custom output buffers are coerced to strings, unless the return value is an array or false
.
- Array return values are converted to
Array
as a literal string. - On a
false
return value, it sets thePHP_OUTPUT_HANDLER_DISABLED
bit for the output handler. - On a
true
return value, it is converted to an empty string.
During the PHP 8.4 development cycle, it was proposed to deprecate this coercing behavior and emit a deprecation notice if a custom output buffer function returned a non-string value. It was not implemented in PHP 8.4, but it is in PHP 8.5 and later.
The documentation for the ob_start()
function, where a custom output buffer is set, indicated that the return value of the function must be string
. This deprecation further enforces it.
ob_start(
static function(string $buffer, int $phase): string {
return (str_replace("hunter2", "****", $buffer));
}
);
echo "hunter2 test";
In PHP 8.5 and later, if the output buffer handler does not return a string
value, PHP emits a deprecation notice:
ob_start(
static function(string $buffer, int $phase) {
return [];
}
);
echo "hunter2 test";
Deprecated: Returning a non-string result from user output handler {closure:...} is deprecated in ... on line ...
Recommended replacement
The ob_start()
function's $callback
parameter expects a callable
that returns a string
. To avoid the deprecation notice, make sure to return a string.
Handlers can return an empty string if the output is already processed/output.
ob_start(
static function(string $buffer, int $phase) {
+ return '';
}
);
Related Changes
Backward Compatibility Impact
In PHP 8.5 and later, custom output buffer handlers that do not return a string
emit a deprecation notice. In PHP 9.0 and later, this may lead to an exception instead.
Returning the processed string, or returning an empty string, is a cross-version compatible fix.