PHP ve bazı global değişkenler

2 Cevap php
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.

Yukarıdaki kod bu hatayı atar:

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 );

2 Cevap

Eğer bir nesne yöntemi içinde $Logger kullanmak istiyorsanız, bu yöntemi içinde küresel olarak işaretlemek gerekir. Eğer yoksa yeni bir yerel $ Logger değişken oluşturarak sona erecek. Ben sorunun ne olduğunu sanıyorum. Örneğin:

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

Ancak, muhtemelen bunu kullanmak için gereken her nesnenin yapıcı $ Logger geçmek için daha iyi olurdu. Global değişkenler genellikle iyi bir uygulama olarak kabul edilmez.

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);

Eğer / şablonlar / list.php başında yere $ Logger unsetting olmadığına emin misin?

Onun başlatmasından sonra ve kullanmadan önce () $ Logger var_dumping sahipsiniz.