【问题标题】:In PHP, how do we get parent class variables?在 PHP 中,我们如何获取父类变量?
【发布时间】:2013-04-06 18:19:19
【问题描述】:

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

【问题讨论】:

  • 你定义了A类两次,B类根本没有……你确定这段代码是正确的吗?
  • 你的意思是class B extends A
  • 对不起,这是一个错字,我更正了它......

标签: php class variables object


【解决方案1】:

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

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();

【讨论】:

  • 这将耗尽内存,因为 B 将被不定式实例化
  • @dev-null-dweller 感谢您的提示!我还没有仔细研究 init 函数并监督它
  • @hek2mgl - 感谢您的代码。我看到调用“parent::init()”似乎是解决方案。
【解决方案2】:

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

【讨论】:

  • 即便如此,这也不是一个解决方案。他会覆盖 init() 方法,这样父类中的那个就不会被调用。
  • 对。他必须在 B 类的 init 函数中调用 parent::init()
  • @xbonez - 调用 init 时,我只能访问该函数中定义的变量吗?
【解决方案3】:

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

parent::$variableName

或者

parent::methodName(arg, list)

【讨论】:

    猜你喜欢
    • 2016-02-26
    • 1970-01-01
    • 2014-09-15
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 2015-06-04
    相关资源
    最近更新 更多