我不确定术语“通配符”是否可以解释我的观点,但有时在一些现成的脚本中,我们可以调用一个非定义的函数,如find_by_age(23),其中age可以是映射到数据库表记录的任何其他内容.所以我可以调用find_by_name,find_by_email,find_by_id等等.那么我们怎么能以程序或面向对象的方式做这样的事情呢?
解决方法:
你正在寻找的术语是魔法.
基本上是这样的:
class Foo {
public function __call($method,$args) {
echo "You were looking for the method $method.\n";
}
}
$foo = new Foo();
$foo->bar(); // prints "You were looking for the method bar."
对于您正在寻找的内容,您只需过滤掉错误的函数调用并重定向好的函数:
class Model {
public function find_by_field_name($field,$value) { ... }
public function __call($method,$args) {
if (substr($method,0,8) === 'find_by_') {
$fn = array($this,'find_by_field_name');
$arguments = array_merge(array(substr($method,8)),$args);
return call_user_func_array($fn,$arguments);
} else {
throw new Exception("Method not found");
}
}
}