gpt4 book ai didi

php - 找出一个方法是 protected 还是公共(public)的

转载 作者:可可西里 更新时间:2023-10-31 22:15:45 25 4
gpt4 key购买 nike

使用这段代码,我试图测试我是否可以调用某些函数

if (method_exists($this, $method))
$this->$method();

但是现在我希望能够在 $method protected 情况下限制执行,我需要做什么?

最佳答案

您需要使用 Reflection .

class Foo { 
public function bar() { }
protected function baz() { }
private function qux() { }
}
$f = new Foo();
$f_reflect = new ReflectionObject($f);
foreach($f_reflect->getMethods() as $method) {
echo $method->name, ": ";
if($method->isPublic()) echo "Public\n";
if($method->isProtected()) echo "Protected\n";
if($method->isPrivate()) echo "Private\n";
}

输出:

bar: Public
baz: Protected
qux: Private

您还可以通过类和函数名实例化 ReflectionMethod 对象:

$bar_reflect = new ReflectionMethod('Foo', 'bar');
echo $bar_reflect->isPublic(); // 1

关于php - 找出一个方法是 protected 还是公共(public)的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5415449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com