0

Debugging PHP: Part I – Type casting

Posted October 27th, 2012 in Razno and tagged , by Metod

Here and there I run into some interesting bugs which I think would be nice to share. So here goes, bug #1 – Type casting.

setSync((int)$type === 'sometype');

// ...

if ($entity->getSync()) {
    // this should be run
}

// ...

Can you spot the problem? That if never gets evaluated. Why?

The problem is here:

$entity->setSync((int)$type === 'sometype');

In this case, the (int) cast only casts the $type variable, not the whole expression. So (int)$type === 0 which definitely is not equal to ‘sometype’ and also since we are using strict checking, type int is not equal to type string. The result is always boolean false.

The correct line should be:

$entity->setSync((int)($type === 'sometype'));

So watch out with casting and parenthesis.