无法访问父类属性

时间:2015-11-10 19:00:32

标签: php inheritance visibility

当我使用父类属性时,它返回--- old.py 2015-11-10 14:01:31.000000000 -0500 +++ new.py 2015-11-10 13:56:52.000000000 -0500 @@ -54,7 +54,7 @@ Keywordencrypt = Keywordencrypt.upper() Keywordencrypt = ord(Keywordencrypt) - 64 CodedMessage = Messageencrypt - Keywordencrypt - if CodedMessage > 90: + if CodedMessage < 65: CodedMessage = CodedMessage + 26 Encryptedletter = chr(CodedMessage) elif Messageencrypt.islower(): @@ -62,7 +62,7 @@ Keywordencrypt = Keywordencrypt.upper() Keywordencrypt = ord(Keywordencrypt) - 64 CodedMessage = Messageencrypt - Keywordencrypt - if CodedMessage > 122: + if CodedMessage < 97: CodedMessage = CodedMessage + 26 Encryptedletter = chr(CodedMessage) else: ,我不知道为什么会发生这种情况,示例代码:

NULL

实际上,当我使用class Foo { public $example_property; public function __construct(){ $this->example_property = $this->get_data(); } public function get_data() { return 22; // this is processed dynamically. } } class Bar extends Foo { public function __construct(){} public function Some_method() { return $this->example_property; // Outputs NULL } } 设置属性值时会发生这种情况,但如果我静态设置值(例如:constructor,则不会再返回public $example_property = 22

1 个答案:

答案 0 :(得分:3)

这是因为应该显式调用父构造函数:

class Bar extends Foo
{
    public function __construct() {
        parent::__construct();
    }


    public function Some_method() {
        return $this->example_property; // Outputs NULL
    }
}

但仔细观察 - 如果你没有声明Bar构造函数,那么应该执行父元素。也许你没有向我们展示完整的代码?

所以,如果你在子类中有__construct并且想要使用父构造函数 - 你应该明确地调用它,就像我所说的parent::__construct();

如果您在儿童课程中没有__construct方法,则会调用父母的方法。