PHP,create_function还是在运行时评估它?

blo*_*low 1 php if-statement class create-function

我有一个类,其中一些方法依赖于一个参数.编写此方法的最佳方法是什么?

例:

第一种方式

class Test{

    var $code;

    function Test($type){
        if($type=="A"){
            $this->code=create_function(/*some args and some code*/);
        }
        else if($type=="B"){
            $this->code=create_function(/*some args and some code*/);
        }
    }

    function use(/*some args*/){
        return call_user_func($this->code,/*some args*/);
    }
}
Run Code Online (Sandbox Code Playgroud)

第二种方式

class Test{

    var $type;

    function Test($type){
        $this->type=$type;
    }

    function use(/*some args*/){
        if($this->type=="A"){
            //some code
        }
        else if($this->type=="B"){
            //some code
        }
    }
}

$test=new Test("A");
$test->use();
Run Code Online (Sandbox Code Playgroud)

你会选择哪种方式?

use*_*291 5

两者都没有(除非你更清楚地解释你所追求的是什么).通常,专用对象被认为比基于属性的分支更好.

class Test {
    abstract function useIt();
}

class TestA extends Test {
    function useIt() { code for A }
}

class TestB extends Test {
    function useIt() { code for B }
}
Run Code Online (Sandbox Code Playgroud)