1

I can't seem to get php to accept dynamic values for parameters when I have a default specified. I've read here that the default value needs to be at the end of the function, which I've done.

$isbilling = true;

function retrieve_address($dbh, $customer_id, $isbilling=false){
echo $isbilling; //false
}

What am I doing wrong here?

Community
  • 1
  • 1
1252748
  • 14,597
  • 32
  • 109
  • 229

3 Answers3

3
$isbilling = true;

function retrieve_address($dbh, $customer_id, $isbilling=false){
echo $isbilling; //false
}

// you have to call your function

retrieve_address('dbhval', 'CUSTID', $isbilling); // will print true
retrieve_address('dbhval', 'CUSTID'); // will print false
iiro
  • 3,132
  • 1
  • 19
  • 22
3

You have set the default value for $isbilling to false, and you aren't passing anything to the $isbilling parameter when you call it (I'm assuming, since you didn't actually post that part).

Try this:

$isbilling = true;

function retrieve_address($dbh, $customer_id, $isbilling=false){
    echo $isbilling; //false
}

retrieve_address($dbh, $customer_id, $isbilling);
Matt Koskela
  • 5,269
  • 3
  • 26
  • 29
0

Well Dynamic values can be any where in the function arguments, and also can be the first ones. But the best practice is to keep them at the end, so you dont have to specify the optional parameter every time you call the function.

I also have changed the echo inside the function to return, this is also a best practice.

$isbilling = true;

function retrieve_address($dbh, $customer_id, $isbilling=false){
     return  $isbilling; //false
}


$returned = retrieve_address($dbh, $customer_id, $isbilling);

So by this you can also do the following

// will return true or false 
if(retrieve_address($dbh, $customer_id, $isbilling)){
    // if it is true, your code
}else{
    // if it is false
}

or

$returned = retrieve_address($dbh, $customer_id, $isbilling);
if(returned)){
    // if it is true, your code
}else{
    // if it is false
}
Aamir Mahmood
  • 2,704
  • 3
  • 27
  • 47