PHP - 在包含文件中使用全局变量进行输出缓冲

PHP - output buffering with global variables in included file

我正在尝试使用输出缓冲来包含一个文件,如下所示。但是不能在包含文件的函数内部使用全局变量。

Main.php

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

test.php - 包含文件:

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
}

首先创建一个class,然后在其中创建函数。例如,让您的文件名为 main.php。然后做这个

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

现在制作另一个文件制作另一个 class。假设您的文件名为 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 
}
}

在class结束后,您可以在class结束后立即调用构造函数中使用的具有相同概念的函数。