Is it a good idea to have all class constructors take in a single array of params, instead of multiple params?
For example,
class A { private $id; private $name; public function __construct($arr) { foreach ($arr as $key => $val) { $this->$key = $val; } } }
instead of
class B { private $id; private $name; public function __construct($id, $name) { $this->id = $id; $this->name = $name; } }
This would eliminate the need to remember the order of arguments, and the need to type $this->key = $val
every time I add a new parameter. Are there any downsides to this method?
Advertisement
Answer
Though this is really opinion, I would not consider it good practice in general to do this. You would lose your ability to enforce the proper call signature at the function/method boundary. You would lose ability to enforce types for parameters passed (or to provide type hinting for IDEs that support this). So something like this cannot be enforced:
function foo ($bar, PDO $pdo_obj) {}
You also lose your ability to provide default parameter values like this:
function foo ($bar, $optional = 'default') {}
You could also potentially expose the method to unexpected behavior. For example, if one were take the approach you suggest in your example. What is to prevent a caller from passing an array of arbitrary length that could exhaust your memory allocation?
Realistically, you shouldn’t even be designing functions that take more than 3 or 4 parameters anyway, so I don’t know what you are really gaining here other than to be able to get “parameters” in undefined order. The cost of this “flexibility” is that you then need to create array wrappers around any parameters you would otherwise pass to a function/method directly.
Finally, I would comment that the approach you suggest is just not typical coding practice within PHP. So, if you ever expect someone else to work with your code, then this approach might be confusing to them, as it is just not something that would typically be encountered.