


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!

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

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 each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

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

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.


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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools