PHP:如何在子构造中调用父构造的私有值?

问题描述 投票:1回答:4

我希望能够在父构造函数中设置私有属性的值,并在子构造函数或方法中调用该值。

例如:

<?php


abstract class MainClass
{
    private $prop_1;
    private $prop_2;


     function __construct()
     {
            $this->prop_2 = 'this is  the "prop_2" property';
     }
}

class SubClass extends MainClass
{
    function __construct()
    {
        parent::__construct();
        $this->prop_1 = 'this is the "prop_1" property';
    }

    public function GetBothProperties()
    {
        return array($this->prop_1, $this->prop_2);
    }

}

$subclass = new SubClass();
print_r($subclass->GetBothProperties());

?>

输出:

Array
(
    [0] => this is the "prop_1" property
    [1] => 
)

但是,如果我将prop_2更改为protected,输出将是:

Array
(
    [0] => this is the "prop_1" property
    [1] => this is  the "prop_2" property
)

我对OO和php有了解,但是我无法弄清楚是什么阻止了prop_2private时被调用(或显示?);它不能是私人/公共/受保护的问题,因为“ prop_1”是私人的,可以调用和显示...对吗? 在子类与父类中分配值是否存在问题?

希望能帮助您理解原因。

谢谢。

我希望能够在父构造函数中设置私有属性的值,并在子构造函数或方法中调用该值。例如:

php inheritance properties private construct
4个回答
6
投票
不能在子类中访问父类的私有属性,反之亦然。

6
投票
如果要从子类访问父级的属性,则必须将受保护的父级属性设置为非私有。这样,它们仍然无法从外部访问。您不能以尝试的方式覆盖子类中父级的私有属性可见性。

2
投票
正如其他人所指出的,您需要将父级的属性更改为protected。但是,另一种方法是为您的父类实现get方法,该方法允许您访问该属性,或者如果希望覆盖它,则可以实现set方法。

0
投票
您有一个使用lambda的简单技巧,我在这里找到了https://www.reddit.com/r/PHP/comments/32x01v/access_private_properties_and_methods_in_php_7/
© www.soinside.com 2019 - 2024. All rights reserved.