Home  >  Article  >  Backend Development  >  [PHP] Several ways to obtain class names and implement singleton mode

[PHP] Several ways to obtain class names and implement singleton mode

little bottle
little bottleOriginal
2019-04-23 09:46:122860browse

Today, the editor will take you to learn how to use PHP to obtain class names and implement singleton mode. It has certain reference value. Interested friends can learn about it!

Several ways to get the class name

1.__CLASS__: Get the current class name

2.get_class(): Return the class name of the object

3.get_called_class(): The name of the late static binding ("Late Static Binding") class, that is, the class name of the static method caller

<?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();
?>

Result:

//结果
foo.__CLASS__:foo
foo.get_class:foo
foo.get_called_class:foo

foo.__CLASS__:foo
foo.get_class:foo
foo.get_called_class:bar

Single case mode: Ensure that a class has only one instance, instantiates itself and provides this instance to the entire system.

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

Related tutorials: PHP video tutorial

The above is the detailed content of [PHP] Several ways to obtain class names and implement singleton mode. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn