I have a multidimensional array with various config settings. Here’s an example:
$this->data = array();
I want this array to be private so I’ve created a getter:
public function getData(){
$args = func_get_args();
$x = $this->data;
foreach($args as $arg) $x = $x[$arg];
return $x;
}
and I use it like this:
$value = $obj->getData('country', 'city', 'street');
Everything works fine but the problem is that it is 5x slower (tested with 100,000 iterations) than direct access:
$value = $obj->data['country']['city']['street'];
What is the best way to do this? Is there any way to make this variable read-only or is there a better way to access it without using foreach()?
You can create getter with
__getmagic method:In such way you can get protected & private properties from anywhere in the same way but set them only inside your class.
If you want only this property to behave in such way, simply use condition:
Of course,
__getis even a bit slower then method getter, but it needs to be called only once for access todataproperty, and every access to any sub-array of it will be as fast as direct access (that means no uglyforeachiterations 🙂 ).