Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

surreal's avatar

PHP Classes Constructors and Child classes (inheritance?)

I'm learning classes and got the following problem, sorry if the title is misleading. I'm still missing many terms:

Calling the index method, it sends "hello" to addToSsml(). 'Hello' gets stored in the array 'addToSsml'. After that I'm initializing(?) the Dev-class and call the world-method in it. World method sends "world" to the addToSsml in the parent class. The problem seems to be: Because of $devclass->method() the parent-constructor gets called again and resets the the array "ssmlArray". The following Output is only "world", not "Hello World".

DevController:

use App\Http\Classes\Dev;
class DevController extends Controller{
    public function __construct(){
        logger("Constructor called!");
        $this->ssmlArray=array();
    }
    public function index(){
        $this->addToSSml("Hello ",false);
        $devclass=new Dev;
        $devclass->method();
	}
    public function addToSsml($ssml,$sendToOutput){
        
        #$ssmlArray[]=$ssml;
        array_push($this->ssmlArray,$ssml);
        logger(json_encode($this->ssmlArray));
        if($sendToOutput==true){
            $ssml="";
            foreach($this->ssmlArray as $singlerow){
                $ssml.=$singlerow;
            }
            print_r(json_encode($ssml));
            
            logger("----");
            exit;
        }
    }
}

Child Class of DevController:

namespace App\Http\Classes;
use App\Http\Controllers\DevController;
class Dev extends DevController{
    public function world(){

        $this->addToSsml("world",true);
    }
    
}

The childclass calles its parent constructor because it has no own constructor. In general all constructor information need to be accessible from nearly every childclass. Is the any sollution that the method/function (addToSsml) collects all incomming strings $ssml and if $sendToOutput is true the method should return/output everything collected at once?

0 likes
2 replies
Funfare's avatar

You having two different Objects, Object one is an instance of DevController instanciated by laravel, Object two you create in the index Method with $devclass = new Dev; So their property ssmlArray are completely independend.

And I think your design of the classes will become a problem. Controllers are only for receiving HTTP Reqeusts and giving output. So if you have an extra class for your logic (the Dev class), this class shoud not extend the Controller

surreal's avatar

@Funfare Oh Okay, that might be an issue. I'll try it with vanilla PHP and see if it works, thank you! edit: Same behaviour. Is the any solution for plain php? Can I fill an array from different classes and childclasses?

Please or to participate in this conversation.