2

我的印象是子类继承了父类的属性。但是,以下是 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"?
    }
}
4

3 回答 3

4

您的代码中有几个错误。我已经纠正了他们。以下脚本应按预期工作。我希望代码注释对您有所帮助:

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();
于 2013-04-06T18:24:50.977 回答
1

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

于 2013-04-06T18:21:09.627 回答
0

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

parent::$variableName

或者

parent::methodName(arg, list)

于 2013-04-06T18:23:47.260 回答