note 90424 deleted from language.oop5.patterns by danbrown
| From: | danbrown@php.net | Date: | Tue, 21 Apr 2009 21:22:56 +0000 |
| Subject: | note 90424 deleted from language.oop5.patterns by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-153559@lists.php.net to get a copy of this message | ||
Note Submitter: costintrifan at yahoo dot no-spam dot com
----
in reply to marshall dot mattingly at NOSPAM dot gmail dot com
This is an example of a Singleton in php 5.2.8
<?php
// php version: 5.2.8
//----------------------------
/**
* class Singleton
*
*/
class Singleton
{
protected static $_instance = NULL; // visible to all subclasses
protected static $e = ''; // visible to all subclasses
private function __clone(){}
protected function __construct(){}
public static function GetInstance()
{
if (is_null(self::$_instance) or !self::$_instance instanceof self)
self::$_instance = new self();
return self::$_instance;
}
public static function SetMsg( $msg = '' )
{
self::$e = $msg;
}
public static function GetMsg()
{
return self::$e;
}
}
/**
* class Extension
*
*/
class Extension extends Singleton
{
/**
* Throws a Fatal Error, because this function is never called in this context
* but of the Singleton's which hasn't this function implemented !
*/
public static function Call()
{
return 'Extension: class '.__CLASS__.' was called!';
}
}
// Test
// #1 instance
$a = Singleton::GetInstance();
$a->SetMsg('hi there! This is instance #1'); // Set the message
$ext = Extension::GetInstance();
$ext->SetMsg('hey'); // change message. This change is visible on all instances
// #2 instance
$b = Singleton::GetInstance();
// change the message again? Will overwrite $ext->SetMsg('hey');
//$b->SetMsg('hi there! This is instance #2');
// #3 instance
$c = Singleton::GetInstance();
echo '$a instance: '.$a->GetMsg().'<br/>';
echo '$b instance: '.$b->GetMsg().'<br/>';
echo '$c instance: '.$c->GetMsg().'<br/>';
echo '$ext instance: '.$ext->GetMsg().'<br/>';
echo '$ext instance call: '.$ext->Call().'<br/>';
/* outputs: */
/*
$a instance: hey
$b instance: hey
$c instance: hey
$ext instance: hey
Fatal error: Call to undefined method Singleton::Call() in
G:\phproot\DesignPatterns\Singleton\class.Singleton.php on line 80
*/
?>
As you can see it works as expected, and the protected properties are visible to subclasses. I
wonder if this really has been changed in php 5.3.0... hmmm..