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

1 php inheritance properties private construct

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

例如:

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

?>
Run Code Online (Sandbox Code Playgroud)

输出:

Array
(
    [0] => this is the "prop_1" property
    [1] => 
)
Run Code Online (Sandbox Code Playgroud)

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

Array
(
    [0] => this is the "prop_1" property
    [1] => this is  the "prop_2" property
)
Run Code Online (Sandbox Code Playgroud)

我有OO和php的基本知识,但我无法弄清楚什么是阻止prop_2被调用(或显示?)的时候private; 它不能是私人/公共/受保护的问题,因为'prop_1'是私有的,能够被调用和显示......对吗?

这是在子类与父类中分配值的问题吗?

我很感激帮助理解为什么.

谢谢.

Gau*_*rav 6

无法在Child类中访问父类的私有属性,反之亦然.

你可以这样做

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


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

   protected function set($name, $value)
   {
        $this->$name = $value;
   }

   protected function get($name)
   {
      return $this->$name;
   }

 }


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

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

}
Run Code Online (Sandbox Code Playgroud)


Jam*_*ler 6

如果要从子类访问父项的属性,则必须使父项的属性受到保护而不是私有.这样他们仍然无法进入外部.您不能以您尝试的方式覆盖子类中父级的私有属性可见性.