


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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 is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
