微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP函数中的通配符

我不确定术语“通配符”是否可以解释我的观点,但有时在一些现成的脚本中,我们可以调用一个非定义的函数,如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");
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐