Comparison of singletons and static methods in PHP object-oriented, and analysis of class automatic loading

PHP中文网
Release: 2016-08-08 09:32:38
Original
1209 people have browsed it

Static Methods:

Example

class A{
	public static function a(){
		# code ...
	}
	public static function b(){
		# code ...
	}
}
// 使用
A::a();
A::b();
Copy after login


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


$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)!


Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template