繁体   English   中英

在PHP中,如何获取父类变量?

[英]In PHP, how do we get parent class variables?

我的印象是子类继承了其父级的属性。 但是,以下内容在类B中为null。有人可以告诉我如何从父类访问属性吗?

$aClass = new A();
$aClass->init();

class A {

    function init() 
    {
        $this->something = 'thing';
        echo $this->something; // thing
        $bClass = new B();
        $bClass->init();
    }

}

class B extends A {

    function init() 
    {
        echo $this->something; // null - why isn't it "thing"?
    }
}

您的代码中有几个错误。 我已经纠正了。 下面的脚本应该可以正常工作。 我希望代码注释对您有所帮助:

class A {

    // even if it is not required you should declare class members
    protected $something;

    function init() 
    {
        $this->something = 'thing';
        echo 'A::init(): ' . $this->something; // thing
    }

}

// B extends A, not A extends B
class B extends A {

    function init() 
    {
        // call parent method to initialize $something
        // otherwise init() would just being overwritten
        parent::init();
        echo 'B::init() ' . $this->something; // "thing"
    }
}


// use class after(!) definition
$aClass = new B(); // initialize an instance of B (not A)
$aClass->init();

您定义的第二个类应该是class B extends A ,而不是class A extends B

我们使用以下语法在PHP中访问父类成员:

parent::$variableName

要么

parent::methodName(arg, list)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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