


Detailed explanation of dynamic instantiation objects in the PHP framework
In framework development, modular development, etc., we may have a need to dynamically instantiate objects when PHP is running.
What is a dynamic instantiation object? Let's first take a look at the concept of a variable function (Variable function) in PHP. For example, the following code:
function foo() { echo 'This is the foo function'; } $bar = 'foo'; $bar();
Running the above code will output "This is the foo function". For details, please refer to the PHP manual: Variable functions. Of course, if you need to call dynamically, then use the call_user_func or call_user_func_array function. The usage of these two functions is not the focus of this article. If you don't understand, please check other information. Back to the topic of this article: What is a dynamically instantiated object? I believe that dynamic instantiation of objects means that the objects that need to be instantiated are dynamically determined (determined by variables) during the run-time of the program (determined by variables), rather than being written directly in the code.
Through the above examples, we already know how to dynamically call a function at runtime. Today, when object orientation is so popular, in some codes, we need to dynamically instantiate a class. What should we do? What to do?
Situation 1: The constructor of the class has no parameters or the number of parameters is determined
If the constructor of the class has no parameters or the class we want to instantiate does not have any parameters at all Without a constructor, it seems simpler. You can change it according to the above example. Well, follow the same example. Who doesn't know:
Code example: (Constructor has no parameters)
class FOO { private $a, $b; public function construct() { $this->a = 1; $this->b = 2; } public function test() { echo 'This is the method test of class FOO<br />'; echo '$this->a=', $this->a, ', $this->b=', $this->b; } } $bar = 'FOO'; $foo = new $bar(); $foo->test();
Run it and you will see the following output:
This is the method test of class FOO $this->a=1, $this->b=2
Well, if we want to pass parameters, then let’s do this:
class FOO { private $a, $b; public function construct($a, $b) { $this->a = $a; $this->b = $b; } public function test() { echo 'This is the method test of class FOO<br />'; echo '$this->a=', $this->a, ', $this->b=', $this->b; } } $bar = 'FOO'; $foo = new $bar('test', 5); $foo->test();
You can also get similar results:
This is the method test of class FOO $this->a=test, $this->b=5
Very ideal.
Situation 2: Class constructionParameters of the functionThe number is uncertain
This situation will be a lot more troublesome, but if you want to write it more universally, just This situation has to be considered. For example, we have the following two classes
class FOO { public function test() { echo 'This is the method test of class FOO'; } } class BAR { private $a, $b; public function construct($a, $b) { $this->a = $a; $this->b = $b; } public function test() { echo 'This is the method test of class BAR<br />'; echo '$this->a=', $this->a, ', $this->b=', $this->b; } }
We want a common way to instantiate these two classes. We noticed that the FOO class does not have a constructor, or it can be considered that the number of parameters of the FOO class's constructor is zero; while the BAR class's constructor has parameters. Fortunately, PHP5 is powerful enough and introduces the concept of reflection. For details, please refer to the PHP manual: Reflection, although there is nothing to refer to in the manual :). Fortunately, the naming is well written. You can already get a rough idea from the class name and method name, so you don’t need too many words.
Okay, let’s use the reflection of PHP5 to start this matter:
(Students who are still using PHP4, please don’t go away. If you have a PHP version without reflection or Is it because of compatibility or because you don’t want to upgrade? Anyway, you don’t want to use reflection. There is a solution below)
$class = new ReflectionClass('FOO'); $foo = $class->newInstance(); //或者是$foo = $class->newInstanceArgs(); $foo->test();
Did you see anything? Next:
$class = new ReflectionClass('BAR'); $bar = $class->newInstanceArgs(array(55, 65)); $bar->test();
OK, it seems OK, so let’s sort it out and create a general function. We want to design it like this. The first function of this function is the name of the class to be instantiated. From the second The first parameter is the parameter of the constructor of the class to be instantiated. If there are several, write them down. If not, don't write them down. To implement a function with a variable number of parameters, we have two methods:
The first is a method similar to:
function foo($arg1, $arg2 = 123, $arg3 = 'test', $arg4 = null, ....... ) { //some code; }
. This method has two disadvantages. First The first is if you need to pass 100 parameters, should you just write 100 parameters? The second is that you have to determine which parameter in the program is null or other default value. (Digression: The default value of the parameter in this way of writing must be placed at the end. You cannot insert a parameter without a default value in the middle or in front of a parameter with a default value. Otherwise, you must also explicitly write the parameter with a default value when you call it. value)
Another way to implement a variable number of parameters is to use PHP's built-in function func_get_args (click here to read the manual) in the function to obtain the parameters passed to the function. Similar functions include func_get_num and func_get_arg. Forget it, I'm lazy. You can find the manual and read it yourself.
Then, it seems to be much more convenient to use this function. Based on our imagined arrangement of function parameters , the code should look like this:
function newInstance() { $arguments = func_get_args(); $className = array_shift($arguments); $class = new ReflectionClass($className); return $class->newInstanceArgs($arguments); }
OK, let’s do it Take a look at the effect:
$foo = newInstance('FOO'); $foo->test(); //输出结果: //This is the method test of class FOO $bar = newInstance('BAR', 3, 5); $bar->test(); //输出结果: //This is the method test of class BAR //$this->a=3, $this->b=5
Just four lines of code, the effect is quite perfect. Then, if applied to a class, we can use this idea and write it directly as Magic Method, which can make our class cooler!
class INSTANCE { function call($className, $arguments) { $class = new ReflectionClass($className); return $class->newInstanceArgs($arguments); } } $inst = new INSTANCE(); $foo = $inst->foo(); $foo->test(); //输出结果: //This is the method test of class FOO $bar = $inst->bar('arg1', 'arg2'); $bar->test(); //输出结果: //This is the method test of class BAR //$this->a=3, $this->b=5
Kaka, feel good.
Next, let’s discuss the situation without using reflection classes. For example, there is no reflection in PHP4, and some old projects run on PHP4. Or if you want to ensure the project's compatibility with unknown environments, whatever, let's take care of how to dynamically transfer parameters. There is only one function for dynamic parameter transfer in PHP: call_user_func_array (click here to view the manual). This is a function that dynamically calls a function. Its function is to pass the parameters of the function to the function to be called in the form of an array. Well, I was confused myself, so let’s look directly at the example:
function foo($a, $b) { echo '$a=', $a, '<br />'; echo '$b=', $b; } call_user_func_array('foo', array(1, 'string')); //本例输出结果: //$a=1 //$b=string
那么,要实现用这种方法来动态实例化对象并传参,呃……,只有曲线救国了,我们得先写一个函数,让这个函数来实例化对象,而这个函数的参数就原原本本地传给要实例化对象的类的构造函数就好了。打住!那这个函数得有几个参数啊?怎么实现传递不同个数的参数呢?嘿嘿,我一声冷笑,你忘了PHP里提供一个创建匿名函数的函数吗?(又开始绕起来了……)create_function(手册在此),照着手册里面的例子直接画就可以了,我也懒得打字了,直接看下面的代码,注释我写清楚点大家都明白了:
function newInst() { //取得所有参数 $arguments = func_get_args(); //弹出第一个参数,这是类名,剩下的都是要传给实例化类的构造函数的参数了 $className = array_shift($arguments); //给所有的参数键值加个前缀 $keys = array_keys($arguments); array_walk($keys, create_function('&$value, $key, $prefix', '$value = $prefix . $value;'), '$arg_'); //动态构造实例化类的函数,主要是动态构造参数的个数 $paramStr = implode(', ',$keys); $newClass=create_function($paramStr, "return new {$className}({$paramStr});"); //实例化对象并返回 return call_user_func_array($newClass, $arguments); }
好了,至于效果是什么,就麻烦各位看官自己动动手,运行一下看看,是不是自己期望的结果。
The above is the detailed content of Detailed explanation of dynamic instantiation objects in the PHP framework. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
