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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.