Is there a way to make a read-only property of an object in PHP? I have an object with a couple arrays in it. I want to access them as I normally would an array
echo $objObject->arrArray[0];
But I don’t want to be able to write to those arrays after they’re constructed. It feels like a PITA to construct a local variable:
$arrArray = $objObject->getArray1();
echo $arrArray[0];
And anyways, while it keeps the array in the object pristine, it doesn’t prevent me from re-writing the local array variable.
Well, the question is where do you want to prevent writing from?
The first step is making the array protected or private to prevent writing from outside of the object scope:
If from "outside" of the array, a GETTER will do you fine. Either:
And accessing it like
or
And accessing it like:
Notice that they don’t return references. So you cannot change the original array from outside the scope of the object. You can change the array itself…
If you really need a fully immutable array, you could use a Object using
ArrayAccess…Or, you could simply extend
ArrayObjectand overwrite all of the writing methods:Then, simply make
$this->arrArrayan instance of the object:It still supports most array like usages:
But if you try to write to it, you’ll get a
LogicException…Oh, but realize that if you need to write to it, all you need to do (within the object) is do: