我有一个类,它有一些依赖于一个参数的方法。 编写此方法的最佳方法是什么?
示例:
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();
您会选择哪种方式?
答案 0 :(得分:5)
既不(除非你更清楚地解释你所追求的是什么)。 通常,专业对象被认为比基于属性的分支更好。
class Test {
abstract function useIt();
}
class TestA extends Test {
function useIt() { code for A }
}
class TestB extends Test {
function useIt() { code for B }
}
答案 1 :(得分:0)
我会选择第二种方式,对于初学者: call_user_func 是一个繁重的函数(最好以其他方式使用),并且代码严格地不是面向对象的方式,而第二种方式是
答案 2 :(得分:0)
感谢答案。
我考虑过这个因为我正在为数据库交互构建一个类。 所以这样做会很好:
$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*/);
再次感谢。