0
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
  • where is your line 99? Could you post it? Commented Aug 27, 2009 at 10:39

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I tried to use global keyword, it didn't help me. Maybe passing it into constructor will be better idea... Okay, thanks.
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.
While a singleton version of Logger might be appropriate, a singleton is just a global variable in disguise
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.