Voting

: five plus four?
(Example: nine)

The Note You're Voting On

janci
18 years ago
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 ;)

<< Back to user notes page

To Top