PHP - 在每个方法调用时调用函数

我有几个带有多种方法的课程。我想用每个方法调用执行一个函数,而不是在每个方法中进行相应的调用。

有没有办法自动执行此操作?像方法侦听器之类的东西?


慕码人2483693
浏览 108回答 1
1回答

慕姐4208626

您可以声明所有方法并像这样private使用魔术方法。__call<?phpclass MyClass{&nbsp; &nbsp; private function doSomething($param1, $param2){ //your previously public method&nbsp; &nbsp; &nbsp; &nbsp;echo "do ".$param1." ".$param2;&nbsp; &nbsp; }&nbsp; &nbsp; private function doSomethingForbidden($param1, $param2){ //your previously public method&nbsp; &nbsp; &nbsp; &nbsp;echo "doSomethingForbidden";&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; private function verifyPermission($methodName){&nbsp; &nbsp; &nbsp; &nbsp;return in_array($methodName, [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "doSomething"&nbsp; &nbsp; &nbsp; &nbsp;]);&nbsp; &nbsp; }&nbsp; &nbsp; public function __call($name, $arguments)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if($this->verifyPermission($name)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return call_user_func_array(array($this, $name), $arguments);&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new \Exception("You can't do that !");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}$nc = new MyClass();$nc->doSomething("pet", "the dog");//do pet the dog$nc->doSomethingForbidden("feed", "the birds");//Fatal error:&nbsp; Uncaught Exception: You can't do that !当方法是私有的或不存在时,PHP 将自动将调用路由到__call存在的方法。call_user_func_array从那里,您可以做您想做的事情(检查权限、记录内容等),并且由于您现在位于类的“内部”,因此您可以使用原始参数自行调用私有方法。您可以阅读魔法方法的文档来了解更多信息https://www.php.net/manual/en/language.oop5.overloading.php#object.call
打开App,查看更多内容
随时随地看视频慕课网APP