2

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?

3
  • 1
    your title should be more specific and well written. because i mistook it as an another post when i saw the title Commented Sep 14, 2015 at 13:10
  • You get a list of ReflectionParameter objects by using getParameters(). You can get the defaults from those objects using class' getDefaultValue method. Commented Sep 14, 2015 at 13:17
  • IDK if this is exaclty what you're looking for, but his might be helpful: geneticcoder.blogspot.com/2015/05/… Commented Sep 14, 2015 at 13:18

1 Answer 1

1

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()
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.