Reputation: 1244
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.
Upvotes: 3
Views: 1283
Reputation: 2915
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
Upvotes: 1
Reputation: 807
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
Upvotes: 1
Reputation: 3121
Pass '0' instead of 0. The former will be a string. You can cast it like this:
$myvar = 0;
u_strasse((string)$myvar);
Upvotes: 0
Reputation: 3932
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
}
Upvotes: 4