PHP and some global variables

2019-08-17 01:37发布

问题:

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.