I'm writing a PHP class and am having considerable trouble defining scope. I've read a lot of articles around this concept on SO, but I can't seem to determine what is the matter with my code.
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 );
This code, when run produces: Call to undefined function write() in /var/www/myfile.php
Any advice on how to create an object which can be referenced in a non static way but is
Replace:
$log.write( "WOW, it's working!!" , 1 );
with:
$log->write( "WOW, it's working!!" , 1 );
$log
is an instance of the class Logger
, and write
is a method of this class.
Documentation: PHP classes and objects