开发者

PHP, create_function or evaluate it at runtime?

开发者 https://www.devze.com 2022-12-09 11:00 出处:网络
I have a class with some method that depend by one parameter. What is the best way to write this method?

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"){
            $thi开发者_运维技巧s->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?


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 }
}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号