Question

class wat
{
   public $a = 3.14;
   public $x = 9;
   public $y = 2;
}


$a = new wat();

var_dump(1000 + $a);
var_dump($a + 1000);

The output is:

int(1001)
int(1001)

Well, adding the wat* object to an integer is obviously not the right thing to do, since PHP complains about it with "Object of class wat could not be converted to int", but still, what does it do?

(I also have a practical reason for asking this, I want to refactor a function to get rid of the "PHP Notice", while still keeping behaviour completely unchanged.)


*: http://img.youtube.com/vi/kXEgk1Hdze0/1.jpg

Was it helpful?

Solution

Addition (+) implicitly casts both operands to float if either one of them is float, otherwise both operands are cast to int (See paragraph #2.)

It seems that, at least for now, an object cast to int results in the value 1, hence the result 1000 + 1 = 1001 or 1 + 1000 = 1001, however, per the documentation, the behavior is undefined and should not be relied upon.

If you've turned on E_NOTICE error reporting, a notice should also be produced, saying that object could not be converted to int.

OTHER TIPS

You're right that you shouldn't cast an Object to an Integer and you can't! Than's why PHP assigns the integer 1 to the variable and should give you a notice which looks like this:

Notice: Object of class foo could not be converted to int in /path/to/file.php on line 1
$foo is now 1
int(1)

to be sure I get the code which actually do the cast:

from Zend/zend_operators.c:

case IS_OBJECT:
    {
    int retval = 1;
        /* some other code */
        ZVAL_LONG(op, retval);  // < This sets the 1 you see.
        return;
    }

so it is not like i said before a internal cast ((int)(boolean)$object) by doing this they preserve semantics of 0,"",NULL,false = false and !0,"...",Object = true

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top