I need to create an immutable class which is simply a member field container. I want its fields to be instantiated once in its constructor (the values should be given as parameters to the constructor). I want the fields to be public but immutable. I could have done it with Java using the final
keyword before each field. How is it done in PHP?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
You could use the
__set()
magic method and throw an exception when someone tries to set a property directly.However, this would prevent modification of properties regardless of whether they're public or not.
magic methods
so you can do better - if you have a dinamyc count of fields
You should use
__set
and__get
magic methods and declare that property as protected or private:Example:
Outputs:
@property-read
should help your IDE acknowledge existence of this magic property.