Home > Article > Backend Development > Two methods of passing PHP implementation classes as parameters
When working on PHP projects, it is often necessary to dynamically use the same method name of a certain class. For example, class A has a get method, and class B also has a get method. At this time, there are only two classes that are very easy to solve. It can be solved perfectly with an if. What if there are N such classes? Then you need the method I will use later to achieve it!
In fact, I only discovered this trick when I was looking at the ThinkPHP framework. That is, PHP can replace a class by its name or its space name. In this case, you can directly pass the class name or the space name of the class to realize the function of passing the class as a parameter.
<?php class A{ public function test(){ $class = 'B'; $b = (new $class); //必须要将类名放在变量里面,如果直接new 'B'会出错。 $b->test(); } }class B{ public function test(){ var_dump('class B'); } }$a = new A();$a->test();//最后将输出class B
//FileA<?php require 'testB.php';class A{ public function test(){ $class = 'testB\B'; $b = (new $class);//必须要将命名空间放在变量里面,如果直接new 'testB\B'会出错。 $b->test(); } }$a = new A();$a->test();
//FileB<?phpnamespace testB; //空间命名class B{ public function test(){ var_dump('testB\B'); } }
Final output: testB\
The above is the detailed content of Two methods of passing PHP implementation classes as parameters. For more information, please follow other related articles on the PHP Chinese website!