Immutable objects in PHP?

后端 未结 6 1256
暗喜
暗喜 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:25

    From an immutable object, you can get its values but there is no way to modify them. Here you can see an example of an immutable class:

    value = $value;
        }
    
        public function value(): string 
        { 
            return $this->value;
        }
    }
    
    // Example of usage:
    $immutable = Immutable::withValue("my value");
    $immutable->value(); 
    

提交回复
热议问题