Search code examples
phpoutput-buffering

PHP - output buffering with global variables in included file


I am trying to include a file using output buffering as follows. But cannot use global variables inside function of an included files.

Main.php

function get_include_contents($filename) {
    if (is_file($filename)) {
        ob_start();
        require $filename;
        return ob_get_clean();
    }
    return false;
}

test.php - included file:

include_once 'settings.php';  // defines many global variables like $obj1, $ojb2

// some processing
test();
// some processing

function test() {
    global $obj1, $obj2;

    // using $obj1
    $obj1->function_obj1();  // $obj1 is not defined
}

Solution

  • First make a class and then create functions in it. For example let your file name be main.php. Then make this

    class main 
    {
    function __construct(){
     // define a constructor 
    }
    function xyz($a1, $a2 ....$an){
    // perform operations 
    } 
    }
    

    Now make another file make another class. Let's say your file name is main2.php

    require_once 'main.php';
    class main2{
    
    private $a1;
    
    function __construct()
    {
         $this->a1 = new main();
    }
    
    function abc()
    {
     $fun = $this->a1->xyz($a1, $a2 ....$an);
    // and now perform operations 
    }
    }
    

    After the class ends, you can call the functions with the same concept used in the constructor right after the class ends.