Links in PHP
In what situations can I use links in PHP? For example, what would be faster:
$get = &$_GET;
echo $get['id']; // это?
$get = $_GET;
echo $get['id']; // или это?
Pozh-ta explain in what cases it is profitable to use links, and then I know about the existence, but I have never used it)
4 answers
Well here's a bunch of examples) The main uses of links are to facilitate code and save memory, because accessing a link does not copy an object.
$arr = array(1, 2, 3);
foreach ($arr as &$v)
$v = 5;
var_dump($arr);
$array = array(array(2, 3, array(15, 16)), array(1, 2, 3))
function &array_get(&$arr) {
$tmp = &$arr;
for ($i = 1; $i < func_num_args(); $i++) {
$code = func_get_arg($i);
if (!isset($tmp[$code])) return false;
$tmp = &$tmp[$code];
}
return $tmp;
}
$var = &array_get($array, 0, 2, 0);
echo $var; // 16
$var = 22; // изменит значение в массиве
function my_recursive_procedure(&$array) {
foreach ($array as &$v)
if (is_array($v)) {
my_recursive_procedure($v);
} else $v = str_replace('a', 'b', $v);
} // без ссылок было бы более громоздко + скопировался бы весь массив
my_recursive_procedure($array);
Before drawing conclusions
Yes, the links are very convenient, and they also save memory
I strongly recommend that you read this thoughtfully and carefully this is
@Sh4dow - why didn't you mention that such code is much worse to read and, when using links, we lose about 30% of performance( in special cases, even more ).
Personally, I, in php, avoid links wherever possible and to you advise...
I also advise anyone who has not read the article by Derik Retans References in PHP
References are needed to pass variables to functions and to work with the variable as a global variable inside the function, but without declaring global $var;