我的SimpleClass:
class Simple
{
private $test;
public function other() {};
public function getTest() {};
public function setTest() {};
public function getSecond() {};
public function setSecond() {};
}
如何从这个课程中获取所有吸气剂?
$ref = new \ReflectionClass(new SimpleClass());
$allMethods = $ref->getMethods();
我怎样才能从$ allMethods获取getter(getTest,getSecond)?
答案 0 :(得分:1)
According to the manual,getMethods方法返回一个数组,因此只需循环遍历它就可以得到你想要的结果。
返回的数组是reflectionMethod objects的数组,因此您甚至可以查看可见性属性 - 即->isPublic()
<?PHP
class Simple
{
private $test;
public function other() {}
public function getTest() {}
public function setTest() {}
public function getSecond() {}
public function setSecond() {}
}
$ref = new \ReflectionClass(new SimpleClass());
$allMethods = $ref->getMethods();
$getters = array();
$publicGetters = array();
for ($methodNum=0; $methodNum < count($allMethods); $methodNum++)
{
if( substr( $allMethods[$methodNum]->getName(), 0, 3 ) == 'get' )
{
$getters[] = $allMethods[$methodNum];
if( $allMethods[$methodNum]->isPublic() )
{
$publicGetters[] = $allMethods[$methodNum];
}
}
}
答案 1 :(得分:0)
首先,在每个类函数之后,不应该有;
,否则会抛出一个语法
语法错误,意外';',期待功能(T_FUNCTION)
现在,要获取getter和setter,您可以遍历这些方法并比较它们的名称:
$getters = array();
$setters = array();
$methods = $ref->getMethods();
foreach($methods as $method){
$name = $method->getName();
if(strpos($name, 'get') === 0)
array_push($getters, $method);
else if(strpos($name, 'set') === 0)
array_push($setters, $method);
}
$getters
的结果将是:
array(2) {
[0]=>
object(ReflectionMethod)#3 (2) {
["name"]=>
string(7) "getTest"
["class"]=>
string(6) "Simple"
}
[1]=>
object(ReflectionMethod)#5 (2) {
["name"]=>
string(9) "getSecond"
["class"]=>
string(6) "Simple"
}
}
$setters
的结果将是:
array(2) {
[0]=>
object(ReflectionMethod)#4 (2) {
["name"]=>
string(7) "setTest"
["class"]=>
string(6) "Simple"
}
[1]=>
object(ReflectionMethod)#6 (2) {
["name"]=>
string(9) "setSecond"
["class"]=>
string(6) "Simple"
}
}
答案 2 :(得分:0)
您可以过滤数组,查找以get
开头的方法,可选择检查它们是public
:
$getMethods = array_filter($allMethods, function($o) {
return stripos($o->name, 'get') === 0
&& $o->isPublic();
});
如果您只想要name
并且不关心public
(PHP 7):
$getMethods = preg_grep('/^get/i', array_column($allMethods, 'name'));
如果你不使用反射,那就容易多了:
$allMethods = get_class_methods('SimpleClass');
$getMethods = preg_grep('/^get/i', $allMethods);