Immutable objects in PHP?

后端 未结 6 1234
暗喜
暗喜 2020-12-31 06:34

Is it a good idea to create objects that cannot be changed in PHP?

For example a date object which has setter methods, but they will always return a new instance of

6条回答
  •  别那么骄傲
    2020-12-31 07:11

    If you want setters on a class and object this is perfectly fine, we do this all of the time as we need to set object data. Just simply don't call it immutable.

    Many things in the dev world are subjective - our approaches, methodology etc - but "immutable" is a pretty solid definition:

    "Immutable":
    - Unchanging over time or unable to be changed.

    If you want an immutable object it means it cannot be changed after instantiation. This is good for things such as data from a DB that needs to remain set in stone for the duration of the cycle.

    If you need to call the object and set or change data on it after instantiation, this is not an immutable object.

    Would you take 2 wheels off a car and calling it a motorbike?

    There is some talk about methods on an "immutable" class being named without the word "set", but this doesn't stop the functionality of them being a method that sets data. You could call it thisDoesNotSetAnything(int $id) and allow data to be passed in which changes the object. It'll be a setter, and thus the object is mutable.

提交回复
热议问题