I don’t know why, but this code worked for me a month ago… maybe I upgraded the php but can’t remember. Tried this with PHP 5.2.17 and 5.3.6
Why is it not possible to use a class object inside the callback of a ob_start function?
<?php
$f=new stdClass();
$f->title="awesome Title";
function callback($buffer)
{
global $f;
$buffer=str_replace("###TITLE###", $f->title, $buffer);
return $buffer;
}
ob_start("callback");
?>
This is the ###TITLE###
Output is:
PHP Notice: Trying to get property of non-object in /Users/qxxx/Sites/test/test.php on line 8
This is the
should be:
This is the awesome Title
This is because the output buffer is being implicitly flushed by the termination of the script.
At this point PHP has already destroyed unreferenced variables, so when it comes to execute your callback function, the variable
$fdoes not exist in the global scope.You can solve this by explicitly flushing the buffer before shutdown starts destroying objects, by placing the following line somewhere in your script.
register_shutdown_function('ob_end_flush');Edit:
I’d like to add that even though this is currently the accepted answer that explains the “why”, the solution provided here does not address the root cause of the issue; the fact that
globalis being used.Many people will tell you that
globalis evil, without giving a reason why. Here you can see one of the reasons.The answer provided by Jack gives a more “best practice” solution (using closures to maintain the variable reference), and should be considered as the proper way to avoid using
globalin new codebases.