Home  >  Article  >  Backend Development  >  Two methods of passing PHP implementation classes as parameters

Two methods of passing PHP implementation classes as parameters

零到壹度
零到壹度Original
2018-04-11 10:44:003407browse

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!

Solution

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.

Replace class by class name

<?php class A{
    public function test(){
        $class = &#39;B&#39;; 
        $b = (new $class); //必须要将类名放在变量里面,如果直接new &#39;B&#39;会出错。
        $b->test();
    }
}class B{
    public function test(){
        var_dump(&#39;class B&#39;);
    }
}$a = new A();$a->test();//最后将输出class B

Replace class by space name

//FileA<?php require  &#39;testB.php&#39;;class A{
    public function test(){
        $class = &#39;testB\B&#39;; 
        $b = (new $class);//必须要将命名空间放在变量里面,如果直接new &#39;testB\B&#39;会出错。
        $b->test();
    }
}$a = new A();$a->test();
//FileB<?phpnamespace testB; //空间命名class B{
    public function test(){
        var_dump(&#39;testB\B&#39;);
    }   
}

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn