Passing object dependencies and variables to objects: Is there a correct order?

For many of my objects, I’m passing in other object dependencies along with variables (strings, integers or arrays). Is there a “best practice” order to pass these into an object? For example, is it better to pass in the variables first, then the objects like this:

function __construct($list, Database $db, Widget $widget) 

Or is it better to pass the dependency objects first like this:

function __construct(Database $db, Widget $widget, $list) 

Or does it not matter at all, and it’s just a personal preference?

1 Like

As with any function, I think for convenience it’s best to first pass required parameters, or those which you will most commonly set explicitly, rather than leaving to the default or omitting.
Otherwise when you want to “skip” a parameter you end up having to do things like: myfunction(NULL, NULL, $param); instead of just: myfunction($param);
I would say the order isn’t really important to PHP, but try to apply some logic and common sense to how you order things for the benefit if the coder.

3 Likes

Also, try to maintain some consistency between similar functions and in your codebase.
Let’s say you already have these functions somewhere in your code:

function do_this(Database $db, $list) {};
function __construct(Widget $widget, $list) {};
function do_that(Database $db, Widget $widget) {};

You’re definitely not going to want to come out of left field with:

function __construct($list, Widget $widget, Database $db) {};

People are going to have to think twice every time they have to call this odd-one-out and its going to be a common source of bugs.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.