phpclassif-statementcreate-function

PHP, create_function or evaluate it at runtime?


I have a class with some method that depend by one parameter. What is the best way to write this method?

Example:

First way

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*/);
    }
}

Second way

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();

Which way you would choose?


Solution

  • neither (unless you explain more clearly what you're after). generally, specialized objects are considered better than property-based branching.

    class Test {
        abstract function useIt();
    }
    
    class TestA extends Test {
        function useIt() { code for A }
    }
    
    class TestB extends Test {
        function useIt() { code for B }
    }