When to use magic method __contructor or set and get

6

My question is regarding builder, for example, I have a class with name, age. the correct one is to use __constructor to pass values to them or use set and get?

    
asked by anonymous 28.12.2014 / 04:10

1 answer

4

First you have to answer if having this data initialized in the instance of the class are fundamental to consider it consistent from the beginning.

The function of the constructor is to create an instance in a valid state from the beginning, that is, not to have access until all important data is initialized.

I will believe that in this case these two data are necessary and therefore must be initialized by the constructor.

Still, nothing prevents you from having setters and getters for them too, especially getter that does something different than the constructor does. Just like even having setter nothing prevents you from using the property referring to it in the constructor, even if it is not fundamental. It is more common to put in the constructors the properties essential for the class but there are also cases that one can put extra properties in the constructor to facilitate the life of the programmer user of the class.

But if you search here, they should not always be used.

    
28.12.2014 / 04:38