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


参考: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];
    }
}

?>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM