This article mainly introduces the simple implementation method of PHP factory mode, briefly explains the concept and principle of factory mode, and analyzes the relevant operating skills of PHP factory mode in the form of examples. Friends in need can refer to it
The example in this article describes the simple implementation method of PHP factory pattern. Share it with everyone for your reference, as follows:
Factory pattern is a class that establishes a factory to create objects as needed. This method is very important in polymorphic programming and allows for dynamic Replace classes, modify configurations, etc.
php sample code is as follows:
//-----------------------------工厂模式-------------------------// class A{ public $class; // public $class = $_GET['c']; //类名 public $method; // public $method = $_GET['m']; //方法 public function __construct($class,$method){ $this->class = ucfirst(strtolower($class)); //对类名进行安全处理 $this->method = strtolower($method); //对方法名进行安全处理 $this->work($this->class,$this->method); } public function work($class,$method){ // 把文件命名成 (类名.class.php的形式),就可以通过类名找到文件。 //include '文件名(文件在别的地方)'; #例如 include './index.php'; 引入文件然后实例化类。 $c = new $class; //实例化类 $c->$method(); //访问类的方法 } } class B{ public function ba(){ echo '实例化后的ba方法<br>'; } public function bb(){ echo '实例化后的bb方法<br>'; } } class C{ public function ca(){ echo '实例化后的ca方法<br>'; } public function cb(){ echo '实例化后的cb方法<br>'; } } //工厂模式的实现 $a = new A('b','ba'); // 通过类访问方法 $a = new A('C','ca'); // 通过类访问方法
Running results:
实例化后的ba方法 实例化后的ca方法
The above is the detailed content of Simple implementation method of PHP factory pattern. For more information, please follow other related articles on the PHP Chinese website!