为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕码人2483693 2023-07-21 18:27:39
我有几个带有多种方法的课程。我想用每个方法调用执行一个函数,而不是在每个方法中进行相应的调用。有没有办法自动执行此操作?像方法侦听器之类的东西?
查看完整描述

1 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

您可以声明所有方法并像这样private使用魔术方法。__call


<?php


class MyClass

{

    private function doSomething($param1, $param2){ //your previously public method

       echo "do ".$param1." ".$param2;

    }

    private function doSomethingForbidden($param1, $param2){ //your previously public method

       echo "doSomethingForbidden";

    } 


    private function verifyPermission($methodName){

       return in_array($methodName, [

          "doSomething"

       ]);

    }


    public function __call($name, $arguments)

    {

        if($this->verifyPermission($name)){

          return call_user_func_array(array($this, $name), $arguments);

        }else{

          throw new \Exception("You can't do that !");

        }

    }

}


$nc = new MyClass();

$nc->doSomething("pet", "the dog");

//do pet the dog

$nc->doSomethingForbidden("feed", "the birds");

//Fatal error:  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


查看完整回答
反对 回复 2023-07-21
  • 1 回答
  • 0 关注
  • 77 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信