Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

Глава 21. Ссылки. Разъяснения

Что такое ссылки

Ссылки в PHP - это средство доступа к содержимому одной переменной под разными именами. Они не похожи на указатели C и не являются псевдонимами таблицы символов. В PHP имя переменной и её содержимое - это разные вещи, поэтому одно содержимое может иметь разные имена. Ближайшая аналогия - имена файлов Unix и файлы - имена переменных являются элементами каталогов, а содержимое переменных это сами файлы. Ссылки в PHP - аналог жёстких ссылок (hardlinks) в файловых системах Unix.



Что делают ссылки> <Exceptions
Last updated: Fri, 26 Jan 2007
 
add a note add a note User Contributed Notes
Ссылки. Разъяснения
henrik at newdawn dot dk
27-Oct-2007 03:21
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
)
rmaj
27-Sep-2007 10:52
<?

$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
riseofthethorax at gmail dot com
01-Jul-2007 03:27
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.
eduardofleury at uol dot com dot br
09-Jun-2007 06:58
<?php
$foo
= 'Hello';
$bar = 'World'
print
$foo . " " . $bar;// Hello World

$foo = &$bar;
$bar = 'Hello My World';

print
$foo;// Hello My World
print $bar;// Hello My World

?>
maghiel at mdijksman dot nl
10-May-2007 04:02
Note that:

Call-time pass-by-reference has been deprecated - argument passed by value; If you would like to pass it by reference, modify the declaration of xxxxx. If you would like to enable call-time pass-by-reference, you can set allow_call_time_pass_reference to true in your INI file. However, future versions may not support this any longer
trucex at gmail dot com
05-May-2007 01:49
In response to Xor and Slava:

I recommend you read up a bit more on the way PHP handles memory management. Take the following code for example:

<?php

$data
= $_POST['lotsofdata'];
$data2 = $data;
$data3 = $data;
$data4 = $data;
$data5 = $data;

?>

Assuming we post 10MB of data to this PHP file, what will PHP do with the memory?

PHP uses a table of sorts that maps variable names to the data that variable refers to in memory. The $_POST superglobal will actually be the first instance of that data in the execution, so it will be the first variable referenced to that data in the memory. It will consume 10MB. Each $data var will simply point to the same data in memory. Until you change that data PHP will NOT duplicate it.

Passing a variable by value does just what I did with each $data var. There is no significant overhead to assigning a new name to the same data. It is only when you modify the data passed to the function that it must allocate memory for the data. Passing a variable by reference will do essentially the same thing when you pass the data to the function, only modifying it will modify the data that is in the memory already versus copying it to a new location in memory.

If for learning purposes you choose to disregard the obvious pointlessness in benchmarking the difference between these two methods of passing arguments, you will need to modify the data when it is passed to the function in order to obtain more accurate results.
sneskid at hotmail dot com
06-Mar-2007 12:47
(v5.1.4)
One cool thing about var_dump is it shows which variables are references (when dumping arrays), symbolized by '
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com
поддержка сайтов тез тур в киеве Z058440144362 Z348613067571