Jump to content

Order of cascading constructor arguments


NotionCommotion

Recommended Posts

Is there any order variables injected in the constructor and then the parent's constructor more typically used than the other or considered best practice?  I believe the last example is less than desired, but feel the first two both have their merits.

EDIT.  I guess if one every uses defaults in a constructor, then the first option is best.

class ParentClass extends ChildClass
{
    public $obj1;
    public function __construct(Class1 $obj1, Class2 $obj2, Class3 $obj3) {
        $this->obj1=$obj1;
        parent::__construct($obj2, $obj3);
    }
}
class ParentClass extends ChildClass
{
    public $obj3;
    public function __construct(Class1 $obj1, Class2 $obj2, Class3 $obj3) {
        $this->obj3=$obj3;
        parent::__construct($obj1, $obj2);
    }
}
class ParentClass extends ChildClass
{
    public $obj2;
    public function __construct(Class1 $obj1, Class2 $obj2, Class3 $obj3) {
        $this->obj2=$obj2;
        parent::__construct($obj1, $obj3);
    }
}

 


 

Link to comment
Share on other sites

It doesn't matter, and there's no particular best practice. Additional parameters often go last but only because that's how it often ends up - optional parameters will force some arrangements, and otherwise general sensibility is more important.

But it is good practice to call the parent constructor as early as possible - ideally as the first statement in the constructor. That ensures the object is set up correctly (as far as the parent class is concerned) before anything else happens.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.