6

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 );
user2864740
  • 60,010
  • 15
  • 145
  • 220
  • I disagree that this is a duplicate of that question. This question asks how to apply *the* default value, given in the parameter list. In this case that would be 'duhok'. (The solution may be the same, but I don't think the question is.) – user2864740 Aug 11 '14 at 06:45
  • @user2864740 , ok. short answer would be: it's not possible. – sectus Aug 11 '14 at 06:48
  • There was proposition: https://wiki.php.net/rfc/skipparams – sectus Aug 11 '14 at 06:50
  • Thanks for answers, @sectus I want way it standard off PHP library. – Dilovan Matini Aug 11 '14 at 07:07

4 Answers4

4

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);
Community
  • 1
  • 1
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
-1

pass null:

abc( 'Dilovan',null, 26 );
serakfalcon
  • 3,501
  • 1
  • 22
  • 33
-1

Test Here

function abc( $name, $city = null, $age = 30 )
{
    if( $city == null )
    {
        $city = 'duhok';
    }

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


abc( 'Dilovan', null, 26 );
baxri
  • 307
  • 1
  • 10
-1

try this

function abc( $name, $city = 'duhok', $age = 30 )
{
    if($city == null || $city == NULL)
    {
        $city = 'duhok'
    }

   echo $name.", ".$city.", ".$age;
}
Satish Sharma
  • 9,547
  • 6
  • 29
  • 51