I have an array in php like this:
$myArray = array(‘name’=>’juank’, ‘age’=>26, ‘config’=>array(‘usertype’=>’admin’,’etc’=>’bla bla’));
I need this array to be accesible along the script to allow changes in any field EXCEPT in the “config” field. Is there a way to protect an array or part of an array from being modified as if it where declared private inside a class? I tried defining it as a constant but it’s value changes during script execution. Implementing it as a class would mean I’d have to rebuild the complete application from scratch :S
thanks!
I do not think you can do this using “pure” “real” arrays.
One way to get to this might be using some class that implements
ArrayInterface; you code would look like it’s using arrays… But it would actually be using objects, with accessor methods that could forbid write-access to some data, I guess…It would have you change a couple of things (creating a class, instanciating it) ; but not everything : access would still be using an array-like syntax.
Something like this might do the trick (adapted from the manual) :
You have to instanciate an object with
new, which is not very array-like… But, after that, you can use it as an array.And when trying to write to an “locked” property, you can throw an Exception, or something like that — btw, declaring a new
Exceptionclass, likeForbiddenWriteException, would be better : would allow to catch those specifically 🙂