简体   繁体   English

PHP Access公共变量从子类收缩

[英]PHP Access public variable changed in constrict from child class

How can I access a public property in Child class that was set by a Parent class with __construct? 如何访问父类使用__construct设置的子类中的公共属性?

For example: 例如:

class Parent
{
    protected $pVariableParent = 'no info'; //This have to be set for all classes

    public function __construct()
    {
        $this->setPVariable(); //Changing the property when class created.
    }

    public function setPVariable(){
        $this->pVariableParent = '123';
    }
}

Class Child extends Parent
{
    public function __construct()
    {
        if(isset($_GET['info']){
            echo $this->pVariableParent;
        }
    }
}

$pInit = new Parent;
$cInit = new Child;

In this state the request site.php/?info shows no info . 在这种状态下,请求site.php/?info显示no info But if I call $this->setPVariable(); 但是如果我调用$this->setPVariable(); from Child, everything works and shows 123 . 来自Child,一切正常,并显示123 Why I can't access already changed property from Parent? 为什么我无法从父级访问已更改的属性? Is it because when I call the Child class it just reads the properties and methods of all parents but doesn't trigger any construct functions? 是因为当我调用Child类时,它只读取所有父级的属性和方法,但不触发任何构造函数吗? And what is the best way to do it? 最好的方法是什么? Thanx. 感谢名单。

The problem is that you overrode the parent constructor, so setPVariable is not called in the child constructor. 问题是您覆盖了父构造函数,因此在子构造函数中未调用setPVariable

To extend the parent constructor instead of override: 扩展父构造函数而不是重写:

Class Child extends Parent
{
  public function __construct()
    {
      parent::__construct();
      if(isset($_GET['info']){
        echo $this->pVariableParent;
    }
  }
}

http://php.net/manual/it/keyword.parent.php http://php.net/manual/it/keyword.parent.php

Let me try to clarify one point: 让我尝试澄清一点:

Why I can't access already changed property from Parent? 为什么我无法从父级访问已更改的属性?

Because the property is not already changed. 因为该属性尚未更改。 You are creating two separate objects; 您正在创建两个单独的对象; $pInit is an instance of the parent class and its property value gets changed in the constructor. $pInit是父类的实例,其属性值在构造函数中更改。 $cInit is an instance of the child class and its property value is unchanged since you override the constructor and the child class does not change the property value. $cInit是子类的实例,并且其属性值未更改,因为您覆盖了构造函数,并且子类不更改属性值。 $pInit and $cInit are not related (except by type), and they certainly don't influence the internal structure of each other. $pInit$cInit不相关(按类型除外),它们当然不会相互影响。

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

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