It is worth noting that the function get_called_class
came into existence from the version 5.3 of PHP.
In addition to the difference of performances as cited by Rafael
class Foo {
public static function bar()
{
echo "\n get_called_class: ";
$time = microtime(true);
echo get_called_class(). ' ';
printf('%f', microtime(true) - $time);
echo "\n static: ";
$time = microtime(true);
echo static::class . ' ';
printf('%f', microtime(true) - $time);
}
}
echo "<pre>";
Foo::bar();
Upshot:
get_called_class: Bar 0.000006
static: Bar 0.000001
There is another issue that needs to be raised.
The get_called_class
is used in partnership with late static binding
frameworks.
For example, when a search framework uses a service system Locator/Ioc, they use the get_called_class
, because this function returns the class name and this can be used to check if there are already instances together with the use of Factorypattern
Example
class Factory
{
private static $_instances = array();
public static function getInstance()
{
$class = get_called_class();
if (!isset(self::$_instances[$class])) {
self::$_instances[$class] = new $class();
}
return self::$_instances[$class];
}
}
class ClassExtendFactory extends Factory {}
$class = ClassExtendFactory::getInstance();
$otherClass = ClassExtendFactory::getInstance();
var_dump($class === $otherClass);
// result true { ou seja, representam o mesmo objeto, duas variáveis apontando para o mesmo endereço de alocamento da memória }
When not using Factory, only use the late static binding
abstract class AbstractExample {
public static function getInstance() {
return new static();
}
}
class Example extends AbstractExample {
}
$ex1 = Example::getInstance();
$ex2 = Example::getInstance();
var_dump($ex1 === $ex2);
// return false { ou seja, agora são 2 instâncias diferentes da mesma class, duas variáveis apontando para espaços diferentes de alocamento na memória }
That’s it, I hope it helped you understand a little better.
It would be because
get_called_class
be available from php5.3 forward? tests this code on https://3v4l.org/ it will run in several versions of php. + 1– rray
PHP 5.3 funfou https://3v4l.org/rmmvc
– Wallace Maxters
And in 5.2 down? gave error or gave another result? do not have access ...
– rray
It showed no results.
– Wallace Maxters