繁体   English   中英

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

[英]PHP: How to call private values of parent construct in child 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());

?>

输出:

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”是私人的,可以调用和显示...对吗?

在子类与父类中分配值是否存在问题?

希望能帮助您理解原因。

谢谢。

父类的私有属性不能在子类中访问,反之亦然。

你可以这样

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'));
    }

}

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

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

因此,在您的父类中,您需要声明:

protected function setProp1( $val ) {
  $this->prop_1 = $val;
}

protected function getProp1() {
  return $this->prop_1;
}

然后,在子类中,可以访问$this->setProp1("someval"); $val = $this->getProp1()

使用lambdas有一个简单的技巧,我在这里找到: https : //www.reddit.com/r/PHP/comments/32x01v/access_private_properties_and_methods_in_php_7/

基本上,您使用lambda并将其绑定到实例,然后可以访问它的私有方法和属性

关于lambda调用的信息: https : //www.php.net/manual/en/closure.call.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM