PHP,create_function 还是在运行时评估它?
我有一个类,其中包含一些依赖于一个参数的方法。 编写此方法的最佳方式是什么?
示例:
第一种方式
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();
您会选择哪种方式?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
两者都不是(除非你更清楚地解释你所追求的是什么)。
一般来说,专用对象被认为比基于属性的分支更好。
neither (unless you explain more clearly what you're after).
generally, specialized objects are considered better than property-based branching.
对于初学者,我会选择第二种方式: call_user_func 是一个繁重的函数(最好以其他方式使用它),并且该代码严格不采用面向对象的方式,而第二种方式是。
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:
But yes, the best way is inheritance and OO, i can do some like this:
Thank again.