php - Increment on "__toString" -
i not sure title should be, code should explain better:
class group { private $number = 20; public function __tostring() { return "$this->number"; } } $number = new group(); echo $number, php_eol; echo ++ $number, php_eol; echo php_eol; $number = "20"; echo $number, php_eol; echo ++ $number, php_eol; echo php_eol; $number = 20; echo $number, php_eol; echo ++ $number, php_eol; output:
20 20 <--- expected 21 20 21 20 21 any idea why got 20 instead of 21? code below works:
$i = null ; echo ++$i ; // output 1 i know group object implements __tostring , expected ++ work string __tostring or @ least throw error
the order in operations happen important:
the variable fetched object, won't casted integer (or else).
this
++operator incrementslval(the long value) ofzval, nothing else. object pointer remains same. internal(fast_)increment_functioncalledzvalhas pointer object, checks type first. if it's object, nothing. whenzvalobject, useful no-operation. won't output warning.only echo instruction performs string cast on arguments:
__tostringmethod called , returns20.20output.
Comments
Post a Comment