简体   繁体   中英

PHP OOP how to access class parent property Scope Resolution Operator (::)?

How can I access property var in class OtherClass from inside class like the method myFunc (parent::myFunc();)

<?php

class MyClass
{
    public $var = 'A';
    protected function myFunc()
    {
        echo "MyClass::myFunc()\n";
    }
}

class OtherClass extends MyClass
{
    public $var = 'B';
    // Override parent's definition
    public function myFunc()
    {
        // But still call the parent function
        parent::myFunc();

        echo "OtherClass::myFunc()\n";
    }
}

$class = new OtherClass();
$class->myFunc();

You cannot, because there's no separate variable. OtherClass extends MyClass therefore OtherClass contains all the MyClass features + additional stuff from OtherClass but whilte keeping access to parent's methods (thru parent:: ) makes perfect sense (ie allows chaining) then having more than one variable of the same name would cause massive headache w/o bringing any benefits.

Create getter and setter methods for var.

class MyClass
{
    private $var = 'A';

    public function getVar()
    {
        return $this->var;
    }

    public function setVar($var)
    {
        $this->var = $var;
    }

    protected function myFunc()
    {
        echo "MyClass::myFunc()\n";
    }
}

You can then either use $this->getVar() in OtherClass if you don't override the getters and setters there. Or if you do, you can use parent::getVar() from within OtherClass .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM