views:

117

answers:

2
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 );
A: 

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.

n1313
+2  A: 

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);
Tom Haigh
I tried to use global keyword, it didn't help me. Maybe passing it into constructor will be better idea... Okay, thanks.
Ockonal
For a Logger and Templateslist class (which both sound like there needs only be one instance of each) I'd suggest using a singleton model. No need to pass variables or using globals.
nikc
While a singleton version of Logger might be appropriate, a singleton is just a global variable in disguise
rojoca