从静态函数访问PHP变量

时间:2015-02-02 06:56:34

标签: php

我在下面的代码中收到错误,导致我无法访问静态函数中的$ log在_construct中初始化的日志。

class Logger extends Singleton{

    protected function __construct() {
        if(!class_exists("Log")) {
            include '/usr/php/Log.php';
        }
        $MONITORING_LOGFILE = "/var/log/Monitoring.log";

        ini_set('error_log', 'syslog');
        openlog($MONITORING_LOGFILE, LOG_NDELAY, LOG_LOCAL0);
        $log = Log::singleton('syslog', LOG_LOCAL0, $MONITORING_LOGFILE, array('lineFormat' => ' %{message}'), PEAR_LOG_DEBUG);
    }


    public static function Log($message){
        $log->err($message);
    }
}

好的,我修改了上面的代码

class Logger extends Singleton{
    private $log;

    protected function __construct() {
        if(!class_exists("Log")) {
            include '/usr/php/Log.php';
        }
        $MONITORING_LOGFILE = "/var/log/Monitoring.log";

        ini_set('error_log', 'syslog');
        openlog($MONITORING_LOGFILE, LOG_NDELAY, LOG_LOCAL0);
        $this->log = Log::singleton('syslog', LOG_LOCAL0, $MONITORING_LOGFILE, array('lineFormat' => ' %{message}'), PEAR_LOG_DEBUG);
    }


    public function Log($message){
        $this->log->err($message);
    }
}

现在它的工作正常......只是想确认在Singleton模式下初始化是否正常?

1 个答案:

答案 0 :(得分:1)

为了能够通过静态函数访问$ log变量,您需要引用它:

class Logger extends Singleton{
    private static $log; //static instance of Log::singleton
    protected function __construct() {
        if(!class_exists("Log")) {
            include '/usr/php/Log.php';
        }
        $MONITORING_LOGFILE = "/var/log/Monitoring.log";

        ini_set('error_log', 'syslog');
        openlog($MONITORING_LOGFILE, LOG_NDELAY, LOG_LOCAL0);
        self::$log = Log::singleton('syslog', LOG_LOCAL0, $MONITORING_LOGFILE, array('lineFormat' => ' %{message}'), PEAR_LOG_DEBUG);
    }

    //static method
    public static function Log($message){
        self::$log->err($message);
    }
}

要创建Logger类的实例并访问静态日志功能,您可以执行以下操作:

$mylog = new Logger();
$mylog::Log("Your text here");