Chris
Chris

Reputation: 1244

Passing 0 to function with default value

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

Answers (4)

DaveyBoy
DaveyBoy

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

a.tereschenkov
a.tereschenkov

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

Stewie
Stewie

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

Ynhockey
Ynhockey

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

Related Questions