How to implement a similar design?

class LogBase { function __construct() {} public function write($message) { fwrite(self::$file, "bla-bla"); } } class Log extends LogBase { private $file = 'address/to/file'; } 

(abbreviated).
That is, I wanted to implement all the functionality in the parent (but not used class), but because I need several different logs, create descendant classes, which will be given the path to the log. But if you use

 Log::write('something'); 

then self::$file in this case leads to the parent class, in which this variable, of course, does not.

    3 answers 3

    Late Static Bindings

    As of PHP 5.3.0, it is a php.

     class A { public static function who() { echo __CLASS__; } public static function test() { static::who(); // Here comes Late Static Bindings } } class B extends A { public static function who() { echo __CLASS__; } } B::test(); 
       class LogBase { protected static $fHandle = false; protected function openFile() { if (self::$fHandle !== false) return true; self::$fHandle = fopen(static::FILE, 'a'); return true; } public static function write($message) { self::openFile(); fwrite(self::$fHandle, $message."\n"); } } class Log extends LogBase { const FILE = 'address_to_file';. } Log::write("sd"); 

      Will work only with 5.3

      What you want is called "later static binding"

      • Thank you very much everyone, I did not know about such a thing. - Oleg Arkhipov

      Try this:

       class LogBase { protected $file; // эта переменная будет доступной в наследниках и в данном классе function __construct($log_file) {$file = $log_file;} public function write($message) { fwrite($file, "bla-bla"); } } class Log extends LogBase { // данный объект можно конструировать, используя родительский конструктор ... } $log = new Log('address/to/file'); // К примеру $log->write("что-то записывается в файл..."); 
      • That's just the point, I need non-instantiated classes (that is, not objects), so you cannot use the constructor. - Oleg Arkhipov
      • In that case, I don't quite understand you. Can you tell us a little more about your task? - AseN 5:34 pm
      • It's simple. I need several logs (they have different files), but the functionality is the same. Namely, I need classes (not objects) for visibility everywhere in the application. PS: I know that there are other ways. - Oleg Arkhipov