PHP,create_function还是在运行时评估它?
-
06-07-2019 - |
题
我有一个类,它有一些依赖于一个参数的方法。 编写此方法的最佳方法是什么?
示例:
第一种方式
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*/);
}
}
第二种方式
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();
您会选择哪种方式?
解决方案
既不(除非你更清楚地解释你所追求的是什么)。 通常,专业对象被认为比基于属性的分支更好。
class Test {
abstract function useIt();
}
class TestA extends Test {
function useIt() { code for A }
}
class TestB extends Test {
function useIt() { code for B }
}
其他提示
对于初学者,我会选择第二种方式: call_user_func 是一个繁重的功能(最好以其他方式使用),并且代码严格地不是以面向对象的方式,而是第二种方式。
感谢答案。
我考虑过这个因为我正在为数据库交互构建一个类。 所以这样做会很好:
$db=new DB(/* host, user etc*/, "mysql");
or
$db=new DB(/* host, user etc*/, "mysqli");
但是,是的,最好的方法是继承和OO,我可以这样做:
$db=new MysqlDB(/* host, user etc*/);
or
$db=new MysqliDB(/* host, user etc*/);
再次感谢。
不隶属于 StackOverflow