note 70025 modified in language.oop5.patterns by danbrown

From: Date: Sun, 23 Jan 2011 16:43:06 +0000
Subject: note 70025 modified in language.oop5.patterns by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-176114@lists.php.net to get a copy of this message
It's sometimes useful to let one sigleton class extend another. You can achieve this by only using static attributes: <?php class A { private static $value = 0; private static $instance = null; private function __construct() { $this->set(time()); } public static function getInstance() { if (is_null((self::$instance))) { $class_name = __CLASS__; self::$instance = new $class_name; } return self::$instance; } private function set($i) { self::$value = $i; $this->out(); } public function out() { echo self::$value; } } class B extends A { public static $instance = null; public static function getInstance() { parent::getInstance(); if (is_null(self::$instance)) { $class = __CLASS__; self::$instance = new $class; } return self::$instance; } } $b = B::getInstance(); $b->out(); ?> This will output the current time twice. If $value isn't static, the call to $b->out() will output 0. Maybe it can save someone some time... --was-- cortex is right - it took me hours to figure it out. None the less it's sometimes useful to let one sigleton class extend another. You can achieve this by only using static attributes: <?php class A { private static $value = 0; private static $instance = null; private function __construct() { $this->set(time()); } public static function getInstance() { if (is_null((self::$instance))) { $class_name = __CLASS__; self::$instance = new $class_name; } return self::$instance; } private function set($i) { self::$value = $i; $this->out(); } public function out() { echo self::$value; } } class B extends A { public static $instance = null; public static function getInstance() { parent::getInstance(); if (is_null(self::$instance)) { $class = __CLASS__; self::$instance = new $class; } return self::$instance; } } $b = B::getInstance(); $b->out(); ?> This will output the current time twice. If $value isn't static, the call to $b->out() will output 0. Maybe it can save someone some time... http://php.net/manual/en/language.oop5.patterns.php

« previous php.notes (#176114) next »