3

Im currently testing a simple PHP function.

I want to to return the currently value of a field if the function is called without any parameter passed or set a new value if a parameter is passed. Strange thing is: if I pass 0 (var_dump is showing correct value int(1) 0), the function goes into the if branch like i called the function without any value and i just don't get why.

function:

public function u_strasse($u_strasse = 'asdjfklhqwef'){
  if($u_strasse == 'asdjfklhqwef'){
    return $this->u_strasse;
  } else {
    // set new value here
  }
}

either u_strasse() or u_strasse(0) gets me in the if branch.

1
  • In the meanwhile I came up with an even better solution, I´m using the default value only PHP reports a warning when calling the function without a parameter and use func_num_args() to choose what to do. if func_num_args() === 0 -> return value, else set new value Commented Mar 25, 2013 at 10:55

4 Answers 4

4

You should use null as the default value:

public function u_strasse($u_strasse = null)
{
    if ($u_strasse === null) { $u_strasse = 'asdjfklhqwef'; }

    // rest of function
}
Sign up to request clarification or add additional context in comments.

1 Comment

Good solution, never tried it with null before so thanks for that. Still i don´t get why PHP is interpreting 0 as default value if it isn´t.
1

When comparing variables of different types (specifically strings and numbers), both values will be converted to a number. Therefore, your 'asdjfklhqwef' converts to 0 (number), the comparison is true.

http://www.php.net/manual/en/language.operators.comparison.php

1 Comment

Thanks. Already had a look at this link but i kinda misslooked this. That was the answer i was looking for :)
1

Use === instead of ==:

public function u_strasse($u_strasse = 'asdjfklhqwef'){
  if($u_strasse === 'asdjfklhqwef'){
    return $this->u_strasse;
  } else {
    // set new value here
  }
}

In case of == php tries to convert 'asdjfklhqwef' to number (because you pass $u_strasse as a number) and (int)'asdjfklhqwef' equals 0. To avoid this behavior you need to compare strictly (===)

Read more about difference in == and === here

Comments

0

Pass '0' instead of 0. The former will be a string. You can cast it like this:

$myvar = 0;

u_strasse((string)$myvar);

2 Comments

I know I´m just curious why 0 is treated as default value. If I test with === it works
PHP will type-convert for you automatically. since you pass in a 0 and that's on the left, the string will be converted to an int as well, and end up being '0' as well. If your string had (say) a '9' as its first character, you'd end up with 0 == 9 and go through the false path.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.