Static Methods:
Example
class A{ public static function a(){ # code ... } public static function b(){ # code ... } } // 使用 A::a(); A::b();
When the script is interpreted, static methods are loaded into memory (and single-copyed). You can use it like a function.
Single case:
In order to realize that only a single copy of a class is stored in the memory, a design pattern is implemented through code using static variables
Example
class Container(){ protected static $loadedSingletonClasses = []; public static function loadSingletonClass($className=''){ if(!isset(self::$loadSingletonClass[$className])){ self::$loadSingletonClass[$className] = new $className; } return self::$loadSingletonClass[$className]; } } $a = Container::loadSingletonClass("foo\bar\MyClass"); $b = Container::loadSingletonClass("foo\bar\MyClass");
$a $b variables in the above code Points to the same memory address, (but if you want to trigger the destructor of the class instantiated by these two variables, you need to destroy both variables. For details, see the knowledge summary in PHP object-oriented)
The difference between singletons and static methods is that static methods will be loaded into memory when the script is interpreted, while singletons will only be loaded into memory when new (provided that both codes are loaded into the memory code area)
Automatic loading:
There is an explanation of automatic loading (the implementation mechanism of autoload in php)
When we
instantiate the class new class
call the static method CLASS::func()
inherited classes and interfaces subClass extends parentClass{}
At this time, the automatic loading function will be triggered:
When we use use to alias the class, the class name passed is also the class before the alias
The above introduces the singleton and object-oriented in PHP Comparison of static methods and analysis of class automatic loading, including aspects of content. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!