教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 【PHP】几种方式实现类名获取以及实现单例模式

【PHP】几种方式实现类名获取以及实现单例模式

发布时间:2020-12-28   编辑:jiaochengji.com
教程集为您提供【PHP】几种方式实现类名获取以及实现单例模式等资源,欢迎您收藏本站,我们将为您提供最新的【PHP】几种方式实现类名获取以及实现单例模式资源

今天小编将带大家学习一下用PHP实现类名获取以及实现单例模式,具有一定的参考价值,感兴趣的朋友可以了解一下!

获取类名的几种方式

1.__CLASS__:获取当前的类名

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

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

<?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

单例模式:确保一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。

<?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];     } } ?>

相关教程:PHP视频教程

以上就是【PHP】几种方式实现类名获取以及实现单例模式的详细内容,更多请关注教程集其它相关文章!

  • 本文原创发布教程集,转载请注明出处,感谢您的尊重!
  • 您可能感兴趣的文章:
    【PHP】几种方式实现类名获取以及实现单例模式
    深入php设计模式实例详解
    php单例模式为何只能实例化一次
    php单例模式有什么用
    【Go】Golang 实现单例模式
    PHP设计模式概述
    php单例模式(Singleton Pattern)实例教程
    php常用的三种设计模式的学习笔记
    详解 PHP 中的三大经典模式
    php获取URL中domain域名的代码一例

    [关闭]
    ~ ~