PHP factory pattern

不言
Release: 2023-03-24 06:50:02
Original
1440 people have browsed it

The content of this article is about PHP factory mode, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

What is factory mode


Factory mode: Create objects of different classes based on different class names.

is a factory that produces objects of different types. Avoid using the new keyword.

It can also be understood as: changing the way to create objects

Factory pattern design requirements

Factory pattern, you can design a factory class

The factory class has a private static property used to save objects of different types

The factory class has a public static method of instantiating objects

Code:

//工厂模式(单例的)

final class Factory{
	//私有的静态的保存对象的数组属性
	static private $arr = array();
	//公共的静态的实例化对象的方法
	public static function getInstance($className){
		//判断当前类的对象是否存在
		if(!isset(self::$arr[$className])){
			self::$arr[$className] = new $className();
		}
		return self::$arr[$className];
	}
}
Copy after login

Related recommendations:

Detailed explanation of PHP singleton design pattern to connect to the database

Detailed example explanation of PHP singleton mode and factory mode



The above is the detailed content of PHP factory pattern. For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!