Search code examples
phpooprequireoutput-buffering

Method inside output buffer not working


Assume having just a trivial snippet:

public function myMethod($file)
{
    require $file;
}

public function capture($file, array $args)
{
    extract($args, EXTR_SKIP);

    ob_start();

    $this->myMethod($file); //not working
    require $file; //works

    return ob_get_clean();
}

Could anyone explain why the snippet above works in case of using require only and not when using the method?


Solution

  • You need to make available the parameters to myMethod:

    public function myMethod($file, array $args)
    {
        extract($args, EXTR_SKIP);
    
        require $file;
    }
    
    public function capture($file, array $args)
    {
        ob_start();
    
        $this->myMethod($file, $args);
    
        return ob_get_clean();
    }
    

    See about the scope of a variable.