Home > Article > Backend Development > PHP factory pattern
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
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, 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]; } }
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!