PHP, create_function or evaluate it at runtime?

830 views Asked by At

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?

3

There are 3 answers

0
user187291 On BEST ANSWER

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 }
}
0
OverLex On

I would choose the second way, for starters: call_user_func is a heavy function (and it is best used in other ways) and that code would be strictly not in an Object Oriented fashion, while the second way it is.

0
blow On

Thank for answers.

I have think about this becouse im building a class for database interaction. So it would be nice can do this:

$db=new DB(/* host, user etc*/, "mysql");
or
$db=new DB(/* host, user etc*/, "mysqli");

But yes, the best way is inheritance and OO, i can do some like this:

$db=new MysqlDB(/* host, user etc*/);
or
$db=new MysqliDB(/* host, user etc*/);

Thank again.