Home > Mobile >  Accessing/Filling PHP array from both partent and child classes
Accessing/Filling PHP array from both partent and child classes

Time:10-14

Given the following code I'd like to add strings to the array ssmlArray via addToOutput method. The problem I'm facing (please correct me if I'm wrong) seems to be when calling $devclass->world(); the parent constructor get also called, resets ssmlArray and the only element within the array is "World".

$dev=new DevController;
$dev->index();

class DevController{
    public function __construct(){
        $this->ssmlArray=array();
    }
    public function index(){
        $this->addToOutput("Hello ",false);
        $devclass=new ChildClass;
        $devclass->world();
    }
    public function addToOutput($ssml,$sendToOutput){
        array_push($this->ssmlArray,$ssml);
        if($sendToOutput==true){
            $ssml="";
            foreach($this->ssmlArray as $singlerow){
                $ssml.=$singlerow;
            }
            print_r(json_encode($ssml));
            exit;
        }
    }
}

#Childclass
class ChildClass extends DevController{
    public function world(){
        $this->addToOutput("world",true);
    }
}

I want to output the entire array as a string at once (only once print_r) and it needs to be fillable from child classes without clearing the contents. Is that even possible?

CodePudding user response:

When you create ChildClass, it calls the parent's __construct if it doesn't have its own __construct. Therefore, $ssmlArray is created again. You can convert it to static variable.

Check it:

<?php
$dev=new DevController;
$dev->index();

class DevController{
    protected static $ssmlArray = [];
    
    public function __construct(){
        
    }
    public function index(){
        $this->addToOutput("Hello ",false);
        $devclass=new ChildClass;
        $devclass->world();
    }
    public function addToOutput($ssml,$sendToOutput){
        array_push(self::$ssmlArray,$ssml);
        if($sendToOutput==true){
            $ssml="";
            foreach(self::$ssmlArray as $singlerow){
                $ssml.=$singlerow;
            }
            print_r(json_encode($ssml));
            exit;
        }
    }
}

#Childclass
class ChildClass extends DevController{
    /*public function __construct(){
        parent::__construct();
    }*/

    public function world(){
        $this->addToOutput("world",true);
    }
}
?>

Demo: https://paiza.io/projects/ZQtGPvPYi8mxNqoitHqS8A

  •  Tags:  
  • php
  • Related