Search code examples
phpautoloadoutput-buffering

PHP __autoload not working within output buffer processing function


I have following dilemma:

ob_start('processBuffer');

function processBuffer($buffer){

    $betterBuffer = SomeClass::doSomething($buffer);
    return $betterBuffer;

}

function __autoload($className){

    if($className == 'SomeClass'){ include_once 'some_class.php'; }

}

If the class SomeClass has to be loaded within processBuffer for the first time, it does not work, but it does work if it has had to be loaded before the processBuffer function is executed. Why is that? Currently, to circumvent this issue, I have to do the following:

__autoload('SomeClass');
ob_start('processBuffer');

How can I fix that?


Solution

  • This is most likely caused by how PHP is layered internally. Your buffer processing function is called at the end of the execution stack, during the output stage. It's similar in that way to error handling functions, which are better documented regarding what they can and can't do. For instance (although I haven't tested this), I expect the buffer processing function also can't echo stuff (well, it can, but the output probably doesn't go anywhere).