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:

  1. the variable fetched object, won't casted integer (or else).

  2. this ++ operator increments lval (the long value) of zval, nothing else. object pointer remains same. internal (fast_)increment_function called zval has pointer object, checks type first. if it's object, nothing. when zval object, useful no-operation. won't output warning.

  3. only echo instruction performs string cast on arguments: __tostring method called , returns 20.

  4. 20 output.


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -