Simple implementation method of PHP factory pattern

不言
Release: 2023-03-28 22:16:01
Original
1553 people have browsed it

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 &#39;实例化后的ba方法<br>&#39;;
 }
 public function bb(){
  echo &#39;实例化后的bb方法<br>&#39;;
 }
}
class C{
 public function ca(){
  echo &#39;实例化后的ca方法<br>&#39;;
 }
 public function cb(){
  echo &#39;实例化后的cb方法<br>&#39;;
 }
}
//工厂模式的实现
$a = new A(&#39;b&#39;,&#39;ba&#39;);  // 通过类访问方法
$a = new A(&#39;C&#39;,&#39;ca&#39;);  // 通过类访问方法
Copy after login

Running results:

实例化后的ba方法
实例化后的ca方法
Copy after login

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!

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