Reputation: 439
I want to get list of methods inside a class as well as their arguments and default values. how can I do that? below is the code that I used:
$class = new ReflectionClass($className);
$methods = [];
foreach($class->getMethods() as $method){
if($method->class == $className && $method->name != '__construct' ){
$obj = [];
$obj['controller'] = $className;
$obj['action'] = $method->name;
$obj['params'] = array_map(function($value){return $value->name;}, $method->getParameters());
$methods[] = $obj;
}
}
The sample result of above code is like:
Array(
[0] => Array
(
[controller] => Controller,
[action] => function,
[params] => Array
(
[0] => offset,
[1] => limit
)
)
)
How can I get function arguments default values?
Upvotes: 2
Views: 444
Reputation: 3202
In your array_map
function for the parameters, you can insert a check whether the parameter has a default value using ->isDefaultValueAvailable()
and if so - list it using ->getDefaultValue()
. See the example below based on your code and change it according to your needs.
Instead of
$obj['params'] = array_map(
function($value){return $value->name;},
$method->getParameters()
);
Use
$obj['params'] = array_map(
function($value){
return $value->name.
($value->isDefaultValueAvailable() ? '='.$value->getDefaultValue() : '');
},
$method->getParameters()
);
Upvotes: 1