【问题标题】:Can't access property from parent class无法从父类访问属性
【发布时间】:2015-11-21 04:14:29
【问题描述】:

我唯一想要实现的是能够从B类访问A类中的Sql属性,但我的理解必须完全离网。

我试过了:

class A {
    public $Sql; /*object*/

    public function __construct() {
        $this->Sql = new MySQLi("localhost", "user", "password", "database");
    }
}

class B extends A {

    public function __construct() {
        $this->foo();
    }

    public function foo() {
        var_dump($this->Sql); // NULL
        var_dump(parent::Sql); // Error due to Sql not being a constant, can't set an object as a constant.
    }

}

$A = new A();
$B = new B();

但是代码并没有像我希望的那样运行。

希望有人能指出我出错的正确方向。

【问题讨论】:

    标签: php oop properties constructor parent


    【解决方案1】:
    $A = new A();
    $B = new B();
    

    上面的这两行创建了两个不同的对象,它们彼此没有任何关系。

    因此,由于您在 B 类中也有一个构造函数,父 constructor doesn't get called implicit,这意味着您必须更改代码并从 B 类中的 A 类调用构造函数,例如

    public function __construct() {
        parent::__construct();
        $this->foo();
    }
    

    【讨论】:

    • 那种清晰的感觉刚刚掠过我,谢谢 - 如果允许,我会在 7 分钟内接受这个答案。
    • @Zanderwar 不客气。享受你的一天:)(顺便说一句:我只能强烈建议您查看链接的手册页。)
    猜你喜欢
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 2017-12-16
    相关资源
    最近更新 更多