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);
    }
}

 


 

Edited by NotionCommotion
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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.