: This article mainly introduces the comparison between single-instance and static methods in php object-oriented, as well as the analysis of automatic class loading. if you are interested in PHP tutorials, please refer. Static method:
Example
Class A {public static function a () {# code ...} public static function B () {# code ...}} // use A: a (); A: B ();
When the script is interpreted, the static method is loaded into the memory (and stored in a single copy ). It can be used like a function.
Singleton:
In order to realize that a class is stored in memory only in a single copy, a design mode implemented by using static variables through code
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");
In the code above, the $ a $ B variable points to the same memory address, (but if you want to trigger the class destructor of the two variables instantiation, you must destroy all these two variables. for details, refer to the php object-oriented knowledge summary)
A singleton is different from a static method in that the static method is loaded to the memory during script interpretation, A singleton is loaded to the memory only when it is new (provided that both codes are loaded to the memory code area)
Automatic loading:
The previous section explains how to automatically load (the implementation mechanism of autoload in php)
When we
Instantiation class new class
Call the static method CLASS: func ()
Inheritance class, interface subClass extends parentClass {}
This will trigger the automatic loading function:
When we use the class with an alias, the passed class name is also the class before the alias
The above section describes the comparison between the single-instance and static methods in php object-oriented, as well as the analysis on automatic class loading, including the following content, for more information, see PHP Chinese website (www.php1.cn )!