Parent class's magic getter doesn't work

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Parent class's magic getter doesn't work

Post 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";
?>
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post by requinix »

parent::__get() may return a value. Your code ignores it.
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

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

Post by anjanesh »

Wow ! I totally missed that. Thanks.
Post Reply