Magic __get in php


i need help about this below:

i understand the code but i do not understand the output of the last line

why the output isb,A,B and notA,b,B ?

class magic{

    public $a = "A";    
    protected $b = array("a" => "A", "b" => "B","c" => "C");
    protected $c = array(1,2,3);

    public function __get($name){
        echo "$name,";
        return $this -> b[$name];


$m = new magic();

echo $m->a;
// A
// because $a is public

echo $m->b;
// b,B
// because $b is protected

echo $m->a.",".$m->b; 
// b,A,B                                                        



The problem is that your echoing the name in your__get() method, this will output the value straight away, but return the value of the variable to display later.

If you change the routine to...

public function __get($name){
    //echo "$name,";
    return "$name,".$this -> b[$name];

Your output becomes -A,b,B

People are also looking for solutions to the problem: PHP POST not working, what module to enable


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.