Naps Posted February 28, 2012 Share Posted February 28, 2012 I am trying to work out why the answer to a PHP quiz question is what it is. The code below prints out: b,c,A,B,C, I just can't seem to get my head round how it works, would anyone be able to talk me through it quickly? Code: <?php class Magic { public $a = "A"; protected $b = array("a" => "A", "b" => "B", "c" => "C"); protected $c = array (1,2,3); public function __get($V) { echo "$V,"; return $this->b[$V]; } public function __set($var, $val) { echo "$var: $val,"; echo $this->$var = $val; } } $m = new Magic(); echo $m->a . "," . $m->b . "," . $m->c . ","; ?> Quote Link to comment https://forums.phpfreaks.com/topic/257931-how-does-this-code-work/ Share on other sites More sharing options...
DavidAM Posted February 28, 2012 Share Posted February 28, 2012 The echo statement in the MAIN code (outside of the class): echo $m->a . "," . $m->b . "," . $m->c . ","; essentially builds a string COMPLETELY and THEN outputs it. In order to build the string, it has to evaluate each of the expressions. $m->a - Accesses the pubic property "a" and places it's value ("A") in the "string" to be output $m->b - Actually calls the "magic" get method which echo's "b,", the returned value, "B" is placed in the "string" to be output $m->c - Actually calls the "magic" get method which echo's "c,", the returned value, "C" is placed in the "string" to be output After evaluating the expressions, the object has output "b,c," and then the echo in the main code outputs "A,B,C,". Since the object's echo's each completed before the main code's echo did, the output is: "b,c,A,B,C," Quote Link to comment https://forums.phpfreaks.com/topic/257931-how-does-this-code-work/#findComment-1322078 Share on other sites More sharing options...
Naps Posted February 28, 2012 Author Share Posted February 28, 2012 Wow thats great I understand now, thanks for the quick response David! Quote Link to comment https://forums.phpfreaks.com/topic/257931-how-does-this-code-work/#findComment-1322081 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.