dstm2014 2016-02-26 00:36
浏览 34
已采纳

将额外(链式)方法调用捕获到__get()魔术方法中

I don't have high hopes for this one:

Given a service that has an action like the foo in $service->foo->bar( $a, $b ) and a container class that has $service as a protected property, is there a way to use __get() on the container to access the service and pass along the ->bar( $a, $b )?

class Container {
  protected $service;
  protected $responses = [];

  public function __get ($name) {
    $this->responses[] = $service->$name-> _???_
    return $resp;
  }
}

that could be intercepted so that the Container could catch the operation, call $service with it, save the response, then return the response

Either some way to grab whatever else is being chained on the $name or if $name just included all of that. I know this is a little convoluted, but it would help me clean some code up substantially, plus I'm just generally curious now.

This app is running PHP7 if that matters.

And alternately, if there is a way to do this but it isn't __get(), insight would be appreciated

  • 写回答

2条回答 默认 最新

  • ds3464 2016-02-26 01:41
    关注

    The call to bar takes place after __get returned. __get is called by the engine so you can't add additional parameters. However you can create additional methods on your container class to implement the feature you want.

    Assuming I understood your question correctly this would result in something like this:

    public function executeOnService(string $name, string $method, ...$args) {
        return call_user_func_array([$this->service->$name, $method], $args);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测