Page 1 of 1

Parent class's magic getter doesn't work

Posted: Sat Jan 05, 2013 1:08 am
by anjanesh
Im not able to understand why this doesn't work fully.

Code: Select all

<?php
class A
{
    protected $_data;   

    public function __get($name)
    {
        if (in_array($name, ['Firstname', 'Lastname']))
         return $this->_data[$name];            
    }   

    public function __set($name, $value)
    {        
        if (in_array($name, ['Firstname', 'Lastname']))
        {
            $this->_data[$name] = $value;
            return;
        }        
    }   
}
class B extends A
{
    public function __get($name)
    {
        parent::__get($name);
        if (in_array($name, ['City', 'Zipcode']))
         return $this->_data[$name];                
    }
    
    public function __set($name, $value)
    {
        parent::__set($name, $value);
        if (in_array($name, ['City', 'Zipcode']))
        {
            $this->_data[$name] = $value;
            return;
        }
    }   
}

$b = new B();
$b->Firstname = "John";
$b->Lastname  = "Smith";
$b->City      = "London";
$b->Zipcode   = "W11 2BQ";

print_r($b);

echo $b->Firstname."\n"; // Doesn't show
echo $b->Lastname."\n"; // Doesn't show
echo $b->City."\n";
echo $b->Zipcode."\n";
?>

Re: Parent class's magic getter doesn't work

Posted: Sat Jan 05, 2013 3:28 am
by requinix
parent::__get() may return a value. Your code ignores it.

Re: Parent class's magic getter doesn't work

Posted: Sat Jan 05, 2013 3:45 am
by anjanesh
Wow ! I totally missed that. Thanks.