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");
        }
    }
}

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...