douchongzhang9267 2013-12-29 14:44
浏览 19
已采纳

PHP在行动之前和行动之后

I would like to know how can I do something similar with beforeAction() and afterAction() from Yii.

I need to have the same behavior in my PHP like those two functions from Yii and I don't know where to start from.

What I really need in my case is that every time a function executes, it has to reload some parameters and after the function executes it's code, it has to set them again.

The first action can be done in the constructor but the second one can only be done using a callback and this is not quite lovely.

I also need to implement this because the number of functions is about 30 and each one is doing something similar. Using this kind of behaviors I'll reduce the code size with about 70%.

function a1(){
  load();
  procA1();
  set();
}

function a2(){
  load();
  procA2();
  set();
}

function a3(){
  load();
  procA3();
  set();
}
and so on...
  • 写回答

1条回答 默认 最新

  • douxiandiyo58855 2013-12-29 15:01
    关注

    Updated: Use call_user_func($function_name, (optional) $parametrs) + magic __call method. It is exactly the same as in Yii.

    public function __call($name,$args) {
       if (method_exists($this,$name)) {
          $this->beforeAction();
          $ret =  call_user_func_array(array($this, $name), $args);
          $this->afterAction();
          return $ret;
       }
    }
    

    Now you can simple call $object->a3(). You can have function named a3 in the class, but add private modifier to it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi