A note for those of you that are using constructs like the following:
return $this->$MyVarName
in your objects.
Consider the following:
class Test {
var $MyArray = array();
function add($var) {
$this->$var[rand(1,100)] = rand(1,100);
}
function show($var) {
echo "nEcho from Test:n";
print_r($this->$var);
}
}
$test = new Test();
$test->show('MyArray');
$test->add('MyArray');
$test->add('MyArray');
$test->add('MyArray');
$test->show('MyArray');
will output
Echo from Test:
Array
(
)
Fatal error: Cannot access empty property in /home/webroot/framework_devhost_dk/compiler/test2.php on line 5
For this to work properly you have to use a construct similar to this:
class Test {
var $MyArray = array();
function add($var) {
$tmp =& $this->$var; //This is the trick... strange but true ;)
$tmp[rand(1,100)] = rand(1,100);
}
function show($var) {
echo "nEcho from Test:n";
print_r($this->$var);
}
}
$test = new Test();
$test->show('MyArray');
$test->add('MyArray');
$test->add('MyArray');
$test->add('MyArray');
$test->show('MyArray');
Will output:
Echo from Test:
Array
(
)
Echo from Test:
Array
(
[19] => 17
[53] => 57
[96] => 43
)
<?
$a = array("a"=>"111", "b"=>"222", "c"=>"333");
foreach ($a as $ix => $val) {
$ref = &$a[$ix];
$ref = $val . '_changed';
}
foreach ($a as $ix => $val) echo "$val ";
// 111_changed 222_changed 333_changed
?>
is a simply way to change elements of array witohut retyping $array_name[$index] all the time
I don't see what the big fuss is, I've used pass
by reference to modify dangling variables in tree structures serializing and deserializing structures to databases.. It seems the reason for this limitation is due to the 99% PHP Newbie syndrome and their lack of pointer experience.. Note the only difference between C and PHP references is there is no pointer arithmetic.. Whether it's an alias or a memory location with the address of another, it's basically the same thing.. If you wanted I could implement tree structures in a linear resizeable array.
What am I supposed to do with
array_walk(&$datastructure,'function');
????
What am I not getting here.. What is the logic behind disabling it.. When did the PHP coders get all theoretical on us.. C is a great language because it keeps the idiots at bay, and allows you to shoot yourself in the foot if you really want to.. If I wanted to protect myself from bad code techniques I'd go write in python or lisp.
Better yet why don't we send the 99% to school to get computer science degrees.
|