PHP类名获取的几种方式及单例模式实现
程序员文章站
2022-05-18 22:44:35
参考:https://www.cnblogs.com/water0729/p/5803217.html
获取类名的几种方式
参考: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]; } } ?>
上一篇: Cmake 学习笔记