PHP and some global variables

岁酱吖の 提交于 2019-12-25 11:35:11

问题


require_once'modules/logger.php';                                                         
$Logger = new Logger();

require_once 'templates/list.php';
$Templates = new templatesList();

require_once 'widgets/list.php';
$Widgets = new widgetsList();

I use $Logger in templates/list.php and in widgets/list.php. $Templates I use in /widgets/list.php.

The code above throws this error:

Notice: Undefined variable: Logger in .../templates/list.php on line 99 Fatal error: Call to a member function toLog() on a non-object in .../templates/list.php on line 99

UPD Here is line 99:

$Logger->toLog( $contentData );

回答1:


If you want to use the $Logger from within an object method, you will need to mark it as global within that method. If you don't you will end up creating a new local $Logger variable. I suspect that is what the problem is. For example:

class templatesList {
    public function __construct() {
        global $Logger;
        //now we can use $logger.
    }
}

However, it would probably be better to pass $Logger into the constructor of every object which needs to use it. Global variables are not generally considered good practise.

class templatesList {
    protected $Logger;
    public function __construct(Logger $Logger) {
        //now we can use $logger.

        //store reference we can use later
        $this->Logger = $Logger;
    }

    public function doSomething() {
        $this->Logger->log('something');
    }
}

new templatesList($Logger);



回答2:


Are you sure you're not unsetting $Logger somewhere in the beginning of /templates/list.php?

Try var_dumping() $Logger after its initialization and before using.



来源:https://stackoverflow.com/questions/1340222/php-and-some-global-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!