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 );
Short answer: that's not possible without writing some code.
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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With