Answer the question
In order to leave comments, you need to log in
Passing parameters to constructor as function arguments or array?
Parameters are passed as arguments:
new Class($param1, $param2, $paramN)
Parameters are passed as an array
new Class(array $params)
How to do better? I have seen both approaches. Perhaps it is worth passing, for example, a singleton that stores all the parameters?
Answer the question
In order to leave comments, you need to log in
Yes, first.
Passing arguments as an array is simply disgusting. Because you have to know / memorize the keys of the array, which is not very good, or rather, terrible.
Imagine if all functions in PHP accepted only one array! What would it be? Could you remember a bunch of keys for every function? No.
Further, the editor will not prompt/show what the method or function should accept. Complicated phpDoc-mentation.
Second.
If your class accepts certain properties, without which the functioning of the class is impossible in full, then you need to write setters and getters. For each property.
This is good and correct practice. Pushing everything into the constructor is not the best idea at all. And setters and getters allow you to change the properties of the class in "real time".
When can you throw an array with parameters into a function or method? In very minor cases, when the omission of one or another element of such an array does not particularly affect anything.
Those. the essence is the following - the class must have a clear and transparent interface. Passing an array is the opposite of such a class.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question