Jump to content

How does this code work?


Naps

Recommended Posts

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 . ",";


?>

Link to comment
https://forums.phpfreaks.com/topic/257931-how-does-this-code-work/
Share on other sites

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,"

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.