darga33
darga33

Reputation: 401

Is it possible to get the value of an overridden NON static member variable of a parent class?

Is it possible to get the value of an overridden NON static member variable of a parent class?

I understand that to get the value of a STATIC member variable you use self::$var1 or ClassName::$var1, but how do you get the value of a NON static member variable?

For instance...

class One
{
public $var1 = 'old var';
}

class Two extends One
{
    public $var1 = 'new var';

    public function getOldVar()
    {
        //somehow get old var
    }
}

Thanks so much in advance!

Upvotes: 3

Views: 277

Answers (2)

user895378
user895378

Reputation:

Nope. Once you've overridden a non-static property value it's gone. You can't use the parent:: syntax with non-static properties like you can with methods.

However, using the static keyword you can utilize PHP's late static binding capabilities to access a static parent property because the static values are bound to the class in which they're assigned:

class Top
{
  public static $prop = 'Parent';
}

class Child extends Top {
  public static $prop = 'Child';

  public static function getParentProp() {
    return parent::$prop;
  }

  public static function getProp() {
    return static::$prop;
  }
}

echo Child::getParentProp(); // outputs "Parent"
echo Child::getProp();       // outputs "Child"

Note that you cannot override a non-static property with a static one in a child class to achieve what you're attempting because PHP (and all other scripting languages, I believe) uses the same table to store property names. This is just a limitation of the language.

Upvotes: 6

FtDRbwLXw6
FtDRbwLXw6

Reputation: 28891

You can do this using reflection:

class One {
    public $var1 = 'old var';
}

class Two extends One {
    public $var1 = 'new var';

    public function getOldVar() {
        $ref = new ReflectionClass(get_parent_class());
        $props = $ref->getDefaultProperties();
        return $props['var1'];
    }
}

$two = new Two;
var_dump($two->getOldVar());  // string(7) "old var"    

Upvotes: 5

Related Questions