php - 在PHP中,我们如何获取父类变量?

标签 php class variables object

我的印象是子类继承其父类的属性。然而,以下是类 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();

关于php - 在PHP中,我们如何获取父类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15854412/

相关文章:

php - 将 PHP 页面转换为静态 HTML 页面的最简单方法

php - Symfony2 bundle 和 Travis-CI

java - ClassNode.accept 上的 NullPointerException

php - 在linux中重新初始化系统范围的环境变量

java - try/catch 中未初始化的变量,带有未处理的异常

java - 将 array_walk 从 php 转换为 java 方法

php -/tmp 目录未在实时服务器上清理

java - 为什么公共(public)类在 android 开发人员滑动 View 示例中的同一个文件中?

class - 从 x86-64 可执行文件中查找类和函数名称

javascript - Firefox 扩展,存储变量值直到 firefox 重新启动