虽然不能区分方法是私有的还是受保护的,但是可以使用
is_callable
. 我把它和“梅兹”的答案作了比较。
所以:
function testIfCallable($object, $method) {
return is_callable(array($object, $method));
}
function testIfCallable2($object, $method) {
if (method_exists($object, $method))
{
$reflection = new ReflectionMethod($object, $method);
return $reflection->isPublic();
}
return false;
}
class Test {
private function privateMethod() {
}
protected function protectedMethod() {
}
public function publicMethod() {
}
public function testAccessibility() {
if (testIfCallable($this, 'privateMethod')) echo "YYY<br>"; else echo 'NNN<br>';
if (testIfCallable($this, 'protectedMethod')) echo "YYY<br>"; else echo 'NNN<br>';
if (testIfCallable($this, 'publicMethod')) echo "YYY<br>"; else echo 'NNN<br>';
}
public function testAccessibility2() {
if (testIfCallable2($this, 'privateMethod')) echo "YYY<br>"; else echo 'NNN<br>';
if (testIfCallable2($this, 'protectedMethod')) echo "YYY<br>"; else echo 'NNN<br>';
if (testIfCallable2($this, 'publicMethod')) echo "YYY<br>"; else echo 'NNN<br>';
}
public function testSpeedAccessibility() {
return $results = [
testIfCallable($this, 'privateMethod'),
testIfCallable($this, 'protectedMethod'),
testIfCallable($this, 'publicMethod')
];
}
public function testSpeedAccesibility2() {
return $results = [
testIfCallable2($this, 'privateMethod'),
testIfCallable2($this, 'protectedMethod'),
testIfCallable2($this, 'publicMethod')
];
}
}
方法
testIfCallable
应该包含在一个公共类或类似的类中,因为不推荐使用全局方法。
我把这个和魔法方法结合使用
__get
和
__set
以确保存在公共的“get/set”方法。
测验:
//Test functionality
$t = new Test();
$t->testAccessibility();
$t->testAccessibility2();
//Test speed
$start = microtime(true);
for($i = 0; $i < 10000; $i++) {
$t->testSpeedAccessibility();
}
echo "Is Callable way: " . (microtime(true) - $start) . "ms<br>";
$start = microtime(true);
for($i = 0; $i < 10000; $i++) {
$t->testSpeedAccesibility2();
}
echo "Reflection way: " . (microtime(true) - $start) . "ms<br>";
输出:
NNN
NNN
YYY
NNN
NNN
YYY
Is Callable way: 0.23506498336792ms
Reflection way: 0.45829010009766ms
最后的想法
如果您需要在所有可见性可能性之间进行测试,您唯一的方法就是使用
testIfCallable2
所以“梅兹”的答案。否则,我的路会快两倍。因为你的问题只是在公众和非公众之间,所以你可以从中受益。这么说,如果你不经常使用它,区别就不显著了。