To yicheng zero-four at gmail dot com: Another, maybe better
example where finding out the real class (not the class we
are in) in static method should be quite usefull is the
Singleton pattern.
There is currently no way how to create an abstract
Singleton class that could be used just by extending it
without the need to change the extended class. Consider this
example:
<?php
abstract class Singleton
{
protected static $__instance = false;
public static function getInstance()
{
if (self::$__instance == false)
{
// This acctually is not what we want, $class will always
be 'Singleton' :(
$class = get_class();
self::$__instance = new $class();
}
return self::$__instance;
}
}
class Foo extends Singleton
{
// ...
}
$single_foo = Foo::getInstance();
?>
This piece of code will result in a fatal error saying:
Cannot instantiate abstract class Singleton in ... on line
11
The best way I figured out how to avoid this requires simple
but still a change of the extended (Foo) class:
<?php
abstract class Singleton
{
protected static $__instance = false;
protected static function getInstance($class)
{
if (self::$__instance == false)
{
if (class_exists($class))
{
self::$__instance = new $class();
}
else
{
throw new Exception('Cannot instantiate undefined class
[' . $class . ']', 1);
}
}
return self::$__instance;
}
}
class Foo extends Singleton
{
// You have to overload the getInstance method in each
extended class:
public static function getInstance()
{
return parent::getInstance(get_class());
}
}
$single_foo = Foo::getInstance();
?>
This is of course nothing horrible, you will propably need
to change something in the extended class anyway (at least
the constructor access), but still... it is just not as nice
as it possibly could be ;)
----
Server IP: 195.46.80.5
Probable Submitter: 158.195.97.203
----
Manual Page -- h
ttp://www.php.net/manual/en/function.get-class.php
Edit -- https://master
.php.net/note/edit/74846
Del: integrated -- h
ttps://master.php.net/note/delete/74846/integrated
Del: useless -- http
s://master.php.net/note/delete/74846/useless
Del: bad code -- htt
ps://master.php.net/note/delete/74846/bad+code
Del: spam -- https:/
/master.php.net/note/delete/74846/spam
Del: non-english --
https://master.php.net/note/delete/74846/non-english
Del: in docs -- http
s://master.php.net/note/delete/74846/in+docs
Del: other reasons-- https://mast
er.php.net/note/delete/74846
Reject -- https://mast
er.php.net/note/reject/74846
Search -- https://
master.php.net/manage/user-notes.php
--
PHP Notes Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub
.php
|