Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP magic methods example

I have this question from the Zend PHP study guide and can't find a proper explanation...

<?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,";
            $this->$var = $val;
        }
    }

    $m = new Magic();
    echo $m->a.",".$m->b.",".$m->c.",";
    $m->c = "CC";
    echo $m->a.",".$m->b.",".$m->c;
?>

According to the guide, solution shall be "b,c,A,B,C,c: CC,b,c,A,B,C". I can't figure out why - maybe you do? My intention is that the first call of $m->a would lead to result "a", but that is obviously wrong...

like image 605
Jan Petzold Avatar asked Dec 09 '11 20:12

Jan Petzold


People also ask

What is __ method __ in PHP?

__FUNCTION__ and __METHOD__ as in PHP 5.0.4 is that. __FUNCTION__ returns only the name of the function. while as __METHOD__ returns the name of the class alongwith the name of the function.

Why it is called magic method in PHP?

Magic methods are special methods which override PHP's default's action when certain actions are performed on an object. All methods names starting with __ are reserved by PHP. Therefore, it is not recommended to use such method names unless overriding PHP's behavior.

What is __ get in PHP?

__get() is utilized for reading data from inaccessible properties.


1 Answers

Since __get() calls echo, some data is being outputted before the echo outside of the class gets called.

Stepping through the first line with echo, this is how it gets executed:

$m->a   "A" is concatenated
","     "," is concatenated
$m->b   "b," is echoed, "B" is concatenated
","     "," is concatenated
$m->c   "c," is echoed, "C" is concatenated
"m"     "," is concatenated

At this point, b,c, has already been echoed, and the string with the value of A,B,Cm is now displayed.

like image 106
Tim Cooper Avatar answered Sep 20 '22 12:09

Tim Cooper