0

i know how to get function parameters.

I am using of course ReflectionMethod to get function parameters but currently i am not able to get default value of those parameter.

this is my code where function is defined

class A{
    public function fn($para1,$para2="not required"){
            //some kind of stuff
    }
}

code for getting function parameter

$meth = new ReflectionMethod("A","fn");
foreach ($meth->getParameters() as $param) {
    //some kind of stuff   
}

now please tell how do i get default value of function parameter

1

2 Answers 2

2

From the docs:

<?php
function foo($test, $bar = 'baz')
{
    echo $test . $bar;
}

$function = new ReflectionFunction('foo');

foreach ($function->getParameters() as $param) {
    echo 'Name: ' . $param->getName() . PHP_EOL;
    if ($param->isOptional()) {
        echo 'Default value: ' . $param->getDefaultValue() . PHP_EOL;
    }
    echo PHP_EOL;
}
?>

http://www.php.net/manual/en/reflectionparameter.getdefaultvalue.php

Sign up to request clarification or add additional context in comments.

2 Comments

but how can i access function which is inside class?
It is the same way, try getDefaultValue() in your posted foreach block. You got the $param value like in the example so $param->getDefaultValue() will show you defaut parameter of method fn in class A.
0

Here is a way you can find the answer quite easily.

$meth = new ReflectionMethod("A","fn");
foreach ($meth->getParameters() as $param) {
        var_dump(get_class_methods(get_class($param)));
}

This will print a list of all available methods, and here are the last few:

[11]=> string(10) "isOptional"
[12]=> string(23) "isDefaultValueAvailable"
[13]=> string(15) "getDefaultValue"

This should give you enough information to figure out the answer. That is, before going to the manual.

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.