从类函数中包含的文件访问全局变量

时间:2015-02-12 13:49:08

标签: php

我正在编写一个基于单个index.php文件的PHP应用程序,该文件使用单个Main类根据请求的页面加载不同的文件。但是,我希望能够从页面文件中访问此Main类实例。

我的index.php看起来有点像这样:

class Main {
    public function init() {
        // Initialisation stuff
    }

    public function runPage() {
        // Obviously there's more to it than this
        $page = "page.php";
        require_once $page;
    }

    public function doUsefulStuff() {
        // ...
    }
}

$main = new Main();
$main->init();
$main->runPage();

在我的page.php文件中,我希望能够访问$main

$foo = $main->doUsefulStuff();

然而,这一行失败了:

  

未定义的变量:第1行的page.php中的main

     

致命错误:在第1行的page.php中的非对象上调用成员函数doUsefulStuff()

有没有办法访问$main变量,或者更好的方法来执行此操作,我错过了?

2 个答案:

答案 0 :(得分:2)

page.php中的代码正在Main实例的上下文中执行。您实际上可以直接访问$this。所以:

$this->doUsefulStuff()

答案 1 :(得分:1)

你所做的并不是最好的想法,但这是另一回事。您遗漏的是您require的代码被有效地粘贴到runPage方法中,因此变量的范围相应。澄清:

//index.php
$someVar = new Main();
$someVar->runPage();

//Main::runPage()
{
    $someVar = 123;//local to this method
    require 'file.php';
}

//include/require file:
echo $someVar;

以上代码将回显123

如果您希望$main成为这些所需文件中Main实例的引用,那么只需添加以下内容:

$main = $this;
require 'thePage.php';

或在所需代码中使用$this

PS:您发布的初始伪代码包含$page = $_GET['page'] . ".php";之类的内容。在某人有这样的代码:这只是要求安全问题。想想如果$_GET['page']之类的话会发生什么:

/etc/passwd #

您需要/etc/passwd

相关问题