简体   繁体   English

从子类访问外部初始化的父类的属性

[英]accessing properties of an externally initialized parent class from a child class

A parent class is constructed from outside the child class, thus, it's constructor cannot be called from inside the child. 父类是从子类外部构造的,因此,不能从子内部调用其构造函数。 How should one go about accessing properties of the parent from the child in this case. 在这种情况下,应该如何从子级访问父级的属性。

Example: 例:

class MyParent {
    protected $args;
    protected $child;

    public function MyParent($args=false){
        $this->args=$args;
        $this->child=new MyChild();
    }
    public function main(){
        $this->child->printArgs();
    }
}

class MyChild extends MyParent{
    public function MyChild(){}
    public function printArgs(){
        Echo "args: ".$this->args['key']." = ".$this->args['value']."\n";
    }
}

$parent=new MyParent(array('key'=>'value'));
$parent->main();

Empty variables are returned when run: 运行时返回空变量:

jgalley@jgalley-debian:~/code/otest$ php run.php 
args:  = 

__construct() is the constructor. __construct()是构造函数。 You are using a variant from ancient PHP4-times. 您使用的是古代PHP4时代的变体。

You instanciate two completely different objects, therefore of course the property $args is completely independent. 您实例化了两个完全不同的对象,因此,当然$args属性是完全独立的。

abstract class MyParent {
    protected $args;

    public function __construct($args=false){
        $this->args=$args;
    }
    public function main(){
        $this->printArgs();
    }
    abstract public function printArgs();
}

class MyChild extends MyParent{
    public function printArgs(){
        Echo "args: ".$this->args['key']." = ".$this->args['value']."\n";
    }
}

$$object=new MyChild(array('key'=>'value'));
$object->main();

This at least works, but a problem is, that I don't know exactly what are the design goals. 至少这是可行的,但问题是我不知道确切的设计目标是什么。 Because it seems to be a kind of cli-Application you should have a look at existing solutions to get an idea, how it could get solved. 因为这似乎是一种cli-Application,所以您应该查看现有的解决方案以获取想法,以及如何解决该想法。

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

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