Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to omit default values of middle parameters when calling a function? [duplicate]

I have function:

function abc( $name, $city = 'duhok', $age = 30 ){

    echo $name.", ".$city.", ".$age;

}

abc( 'Dilovan', null, 26 ); // output: Dilovan, , 26

And I want to output will:Dilovan, duhok, 26

I want way to use this function without set second argument and the second argument write default value.

abc( 'Dilovan', [what i use here to write defualt value ?], 26 );
like image 587
Dilovan Matini Avatar asked Aug 11 '14 06:08

Dilovan Matini


1 Answers

Short answer: that's not possible without writing some code.

Solution 1

Add this logic to your function body instead of the declaration; for instance:

function abc($name, $city = null, $age = 30)
{
    $city = $city !== null ? $city : 'duhok';
    // rest of your code
}

Then you can call the function like so:

abc('Dilovan', null, 29);

This will assign the default value if the given $city is null.

Solution 2

You can use Reflection to find out what the default value of a parameter is:

$rf = new ReflectionFunction('abc');
$params = $rf->getParameters();

$default_city = $params[1]->getDefaultValue();

abc('Dilovan', $default_city, 26);
like image 146
Ja͢ck Avatar answered Oct 14 '22 09:10

Ja͢ck