1

我正在编写一个 PHP 类,并且在定义范围时遇到了相当大的麻烦。我在 SO 上阅读了很多关于这个概念的文章,但我似乎无法确定我的代码有什么问题。

class Logger {

    private static $logger ;
    private $res ;
    private $file ;
    private $mode ;

public static function getInstance() {
    if (!self::$logger) $instance = new self() ;
    self::$logger = $instance ;
    return self::$logger ;
}

private function initializeLogger( ) {

    $this->file = '/tmp/mydirectory/mylog.log' ;
    $this->res =  fopen($this->file, 'a') or exit("Can't open ".$this->file);
}


public function write( $message , $modeLevel ) {

    if ( !is_resource($this->res )) {
        $this->initializeLogger( ) ;
    }

    fwrite($this->res, "$message" . PHP_EOL);

}

public function close()
{
    fclose(self::$logger);
}
}


$log = Logger::getInstance();
$log.write( "WOW, it's working!!" , 1 );

此代码在运行时会产生: Call to undefined function write() in /var/www/myfile.php

关于如何创建可以以非静态方式引用的对象的任何建议,但

4

1 回答 1

3

代替:

$log.write( "WOW, it's working!!" , 1 );

和:

$log->write( "WOW, it's working!!" , 1 );

$log是类的一个实例,Loggerwrite这个类的一个方法。

文档:PHP 类和对象

于 2012-11-23T00:13:50.197 回答