user2907171
user2907171

Reputation: 315

get function parameter with default value

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

Upvotes: 0

Views: 840

Answers (2)

Vlad Preda
Vlad Preda

Reputation: 9910

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.

Upvotes: 0

steven
steven

Reputation: 4875

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

Upvotes: 2

Related Questions