PHP类名获取的几种方式及单例模式实现

时间:2022-05-12 03:51:00

参考:https://www.cnblogs.com/water0729/p/5803217.html

<?php

class foo {
static public function test() {
echo "foo.__CLASS__:".__CLASS__."\n";
echo "foo.get_class:".get_class()."\n";
echo "foo.get_called_class:".get_called_class()."\n";
}
} class bar extends foo { } foo::test();
echo "\n";
bar::test();
?>
//结果
foo.__CLASS__:foo
foo.get_class:foo
foo.get_called_class:foo foo.__CLASS__:foo
foo.get_class:foo
foo.get_called_class:bar

获取类名的几种方式

1.__CLASS__:获取当前的类名

2.get_class():返回对象的类名

3.get_called_class():后期静态绑定("Late Static Binding")类的名称,即静态方法调用者的类名

<?php

//通过get_called_class实现单例模式

class Singleton{

   private static $instance;
  
public static function getInstance() {
$class_name = get_called_class();
if (isset(self::$instance[$class_name])) {
return self::$instance[$class_name];
}
self::$instance[$class_name] = new $class_name;
return self::$instance[$class_name];
}
} ?>