php PHP如何列出类的所有公共函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11575724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP how to list out all public functions of class
提问by Kristian
I've heard of get_class_methods()but is there a way in PHP to gather an array of all of the public methods from a particular class?
我听说过,get_class_methods()但在 PHP 中有没有办法从特定类中收集所有公共方法的数组?
回答by Alex Barnes
Yes you can, take a look at the reflection classes / methods.
是的,你可以,看看反射类/方法。
http://php.net/manual/en/book.reflection.phpand http://www.php.net/manual/en/reflectionclass.getmethods.php
http://php.net/manual/en/book.reflection.php和 http://www.php.net/manual/en/reflectionclass.getmethods.php
$class = new ReflectionClass('Apple');
$methods = $class->getMethods(ReflectionMethod::IS_PUBLIC);
var_dump($methods);
回答by Diego Agulló
As get_class_methods()is scope-sensitive, you can get all the public methods of a class just by calling the function from outside the class' scope:
由于get_class_methods()范围敏感,您可以通过从类的范围之外调用函数来获取类的所有公共方法:
So, take this class:
所以,上这门课:
class Foo {
private function bar() {
var_dump(get_class_methods($this));
}
public function baz() {}
public function __construct() {
$this->bar();
}
}
var_dump(get_class_methods('Foo'));will output the following:
var_dump(get_class_methods('Foo'));将输出以下内容:
array
0 => string 'baz' (length=3)
1 => string '__construct' (length=11)
While a call from inside the scope of the class (new Foo;) would return:
虽然来自类 ( new Foo;)范围内的调用将返回:
array
0 => string 'bar' (length=3)
1 => string 'baz' (length=3)
2 => string '__construct' (length=11)
回答by Adi
After getting all the methods with get_class_methods($theClass)you can loop through them with something like this:
获得所有方法后,get_class_methods($theClass)您可以使用以下内容循环它们:
foreach ($methods as $method) {
$reflect = new ReflectionMethod($theClass, $method);
if ($reflect->isPublic()) {
}
}
回答by GBD
Have you try this way?
你试过这种方法吗?
$class_methods = get_class_methods(new myclass());
foreach ($class_methods as $method_name) {
echo "$method_name\n";
}

