Greetings all!
I'm having a problem with trying to add elements to an array property accessed via a variable. The following dummy code illustrates the problem:
The idea is that the setArrayValue method will take a property name as a string ($prop) and create it as an empty array if it doesn't exists. Then it sets the $key element of that array to $val. However, that's not what actually happens. The above program prints out:
As far as I can tell, PHP is treating the $prop[$key] portion of the array assignment as a string subscript and evaluating it as the first character of $prop. So instead of setting $b->foo->Fizz['Buzz'], it sets $b->foo->F.
Is there some syntax I don't know about that will force PHP to interpret $prop[$key] as an array element instead of a character in a string? Anyone know which, if any, section of the manual covers this? I can trivially work around the problem by using array_merge() instead assigning to an element, but that feels a little too ad hoc for my taste. It seems like there ought to be a better way to do it.
I'm having a problem with trying to add elements to an array property accessed via a variable. The following dummy code illustrates the problem:
Code:
<?php
class foo { }
class bar {
function bar() {
$this->foo = new foo;
}
function setArrayValue($prop, $key, $val) {
if (! isset($this->foo->$prop)) {
$this->foo->$prop = array();
}
$this->foo->$prop[$key] = $val;
}
}
$b = new bar;
$b->setArrayValue('Fizz', 'Buzz', 'Bazz');
$b->setArrayValue('abc', 'def', 'ghi');
var_dump($b);
?>
Code:
object(bar)(1) {
["foo"]=>
object(foo)(4) {
["Fizz"]=>
array(0) {
}
["F"]=>
string(4) "Bazz"
["abc"]=>
array(0) {
}
["a"]=>
string(3) "ghi"
}
}
Is there some syntax I don't know about that will force PHP to interpret $prop[$key] as an array element instead of a character in a string? Anyone know which, if any, section of the manual covers this? I can trivially work around the problem by using array_merge() instead assigning to an element, but that feels a little too ad hoc for my taste. It seems like there ought to be a better way to do it.