このコードを使用して、特定の関数を呼び出すことができるかどうかをテストしようとしています
if (method_exists($this, $method))
$this->$method();
ただし、 $method が保護されている場合に実行を制限できるようにしたいのですが、どうすればよいですか?
このコードを使用して、特定の関数を呼び出すことができるかどうかをテストしようとしています
if (method_exists($this, $method))
$this->$method();
ただし、 $method が保護されている場合に実行を制限できるようにしたいのですが、どうすればよいですか?
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
ReflectionMethod を使用する必要があります。isProtected
とisPublic
を使用できますgetModifiers
http://www.php.net/manual/en/class.reflectionmethod.php http://www.php.net/manual/en/reflectionmethod.getmodifiers.php
$rm = new ReflectionMethod($this, $method); //first argument can be string name of class or an instance of it. i had get_class here before but its unnecessary
$isPublic = $rm->isPublic();
$isProtected = $rm->isProtected();
$modifierInt = $rm->getModifiers();
$isPublic2 = $modifierInt & 256; $isProtected2 = $modifierInt & 512;
メソッドが存在するかどうかの確認については、ReflectionMethod を使用して現在行っているように行うmethod_exists
か、単に ReflectionMethod を構築しようとするだけで、存在しない場合は例外がスローされます。 必要に応じて、クラスのすべてのメソッドの配列を取得ReflectionClass
する関数があります。getMethods
免責事項 - 私は PHP Reflection についてよく知りません。ReflectionClass などでこれを行うより直接的な方法があるかもしれません。