1 回答
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
- 1 回答
- 0 关注
- 107 浏览
添加回答
举报