php里面__call方法的妙用
- 实现链式调用:
class Chainable {
private $value;
public function __construct($value) {
$this->value = $value;
}
public function __call($method, $args) {
// 处理方法的返回值
$this->value = call_user_func_array([$this->value, $method], $args);
return $this; // 返回当前对象,以便支持链式调用
}
}
// 链式调用示例
$value = "hello";
$chainable = new Chainable($value);
$result = $chainable->strtoupper()->substr(0, 5)->strrev()->getValue();
echo $result; // 输出结果为 "OLLEH"
通过__call方法,可以在对象的方法链中灵活地处理方法的返回值,实现更加流畅的链式调用。
- 统一处理,使用代理模式,拦截调用,可在调用前后增加其他逻辑,比如检查数据有效性,打印日志等统一的处理,示例如下
public function __call($name, $arguments)
{
if (!method_exists($this, $name)) {
return $this->response(0, '调用方法不存在');
}
//判断服务商是否存在
if (!$this->shop) {
return $this->response(0, '服务商不存在');
}
//验证服务商状态
if ($this->shop['status'] != 1) {
return $this->response(0, '服务商状态错误');
}
//判断服务商是否集成,并检查他的接口地址是否存在,不满足条件直接返回错误
if($this->shop->integrate=='否'){
return $this->response(-1, '服务商未集成,请正常处理');
}
if (!$this->shop->api_address) {
return $this->response(0, '服务商为接口用户,但接口地址为空');
}
//检查接口地址有效性,必须是有效的http地址
if (!filter_var($this->shop->api_address, FILTER_VALIDATE_URL)) {
return $this->response(0, '服务商为接口用户,但接口地址无效');
}
//检查key是否设置
if (!$this->shop->key) {
return $this->response(0, '服务商为接口用户,但服务商key为空');
}
return call_user_func_array([$this, $name], $arguments);
}