简体   繁体   中英

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. You are using a variant from ancient PHP4-times.

You instanciate two completely different objects, therefore of course the property $args is completely independent.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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