My SimpleClass:
class Simple
{
private $test;
public function other() {};
public function getTest() {};
public function setTest() {};
public function getSecond() {};
public function setSecond() {};
}
How to get from this class all getters?
$ref = new \ReflectionClass(new SimpleClass());
$allMethods = $ref->getMethods();
And how can I get from $allMethods only getters (getTest, getSecond)?
According to the manual, the getMethods method returns an array so simply looping across it should yield what you want.
The returned array is an array of reflectionMethod objects so you could even look at the visibility properties - i.e. ->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];
}
}
}
First of all, after each of your class functions, there shouldn't be a ;
, otherwise it will throw a Syntax
syntax error, unexpected ';', expecting function (T_FUNCTION)
Now, to get the getters and setters, you can loop through the methods and compare their names:
$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);
}
And the result of $getters
will be:
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"
}
}
And the result of $setters
will be:
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"
}
}
You can filter the array looking for methods starting with get
, optionally checking if they are public
:
$getMethods = array_filter($allMethods, function($o) {
return stripos($o->name, 'get') === 0
&& $o->isPublic();
});
If you only want the name
and aren't concerned with public
(PHP 7):
$getMethods = preg_grep('/^get/i', array_column($allMethods, 'name'));
A bit easier if you don't use reflection:
$allMethods = get_class_methods('SimpleClass');
$getMethods = preg_grep('/^get/i', $allMethods);