vulkoingim
vulkoingim

Reputation: 117

Calling function with TRUE returns wrong thing

I have this function

//$hasher is a phpass object.    
public function getHash( $check )
    {
    global $hasher;
    if ( $check == 'hash' )
        {
        return $hasher->HashPassword($this->password);
        }
    else if ( $check == 'check' )
        {
        return $hasher->CheckPassword($this->password, $this->getData('data')['password']);
        }
    else
        {
        return 'F*** off';
        }
    }

When i call it this is what i get

$obj->getHash('hash')
//getHash(): $2a$08$Uof.EzLkJI..........

$obj->getHash('check')
//getHash(): 1

$obj->getHash('dsadaldas') //and anything else in the brackets
//getHash():F*** off

$obj->getHash(TRUE)
//getHash(): $2a$08$3vNYnGVsf...

Why does calling the method with TRUE return the same as if i had called it with 'hash' as an argument? Am i missing something here? I tried it with switch() and it still behaves the same.

Upvotes: 1

Views: 34

Answers (2)

Fabian Schmengler
Fabian Schmengler

Reputation: 24551

It's because when you compare boolean (true) to string ("hash"), the string gets converted to boolean, not the other way around.

Solution: use type-safe comparison (===)

Upvotes: 0

MrCode
MrCode

Reputation: 64526

Because a string such as hash evaluates to true when you use the equality operator (==):

You could use the identical (===) operator instead:

if ( $check === 'hash' )

This ensures that both the value of the variable and the type are the same.

Upvotes: 2

Related Questions