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

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

little bottle
Release: 2023-04-06 09:02:01
Original
2909 people have browsed it

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

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
Copy after login

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template