This article mainly introduces the simple implementation of the PHP Factory mode, simple explanation of the concept of the factory model, the principle and combined with examples of PHP implementation of the factory model of the relevant operating skills, the need for friends can refer to the following
In this paper, a simple implementation method of PHP Factory mode is described. Share to everyone for your reference, as follows:
Factory mode is a class that builds a factory to create objects based on what is needed, which is important in polymorphic programming, allowing dynamic substitution of classes, modification of configurations, and so on.
The PHP sample code is as follows:
-----------------------------Factory mode-------------------------//class a{public $class; Public $class = $_get[' C '); Class name public $method; Public $method = $_get[' m ']; Method Public Function __construct ($class, $method) { $this->class = Ucfirst (Strtolower ($class));//safe handling of class names $this->method = Strtolower ($method); The method name is handled securely $this->work ($this->class, $this->method);} Public function work ($class, $method) { // Name the file (in the form of class name. class.php), and you can find the file by the class name. //include ' filename (file in another place) '; #例如 include './index.php '; Introduce the file and instantiate the class. $c = new $class;//Instantiation Class $c-$method ();//method of accessing the class}}class b{public Function ba () { echo ' after instantiating the BA method <BR&G t; '; } public Function bb () { echo ' instanced bb method <br> ';}} Class c{Public Function Ca () { echo ' after instantiation of CA method <br> ';} public Function cb () { echo ' after instantiation of CB method <br> '; }}//the implementation of the Factory mode $ A = new A (' B ', ' BA '); Through the class access method $ A = new A (' C ', ' Ca '); Through the class access method
Operation Result:
The BA method after instantiation
The CA method after instantiation
Articles you may be interested in:
PHP Custom Function Implementation assign () array assigned to template and extract () variable assignment to template function example
Analysis of basic design idea and realization method of MVC framework based on PHP imitation TP
Yii2 Installing the detailed process _php instance