Links in PHP

Lecture



Although there is no such thing as a pointer in PHP, it is still possible to create references to other variables. There are two types of links: hard and symbolic (variable variables) (the former are often called simply links). Hard links appeared in PHP version 4 (in the third version, only symbolic links existed).

Links in PHP are a means of accessing the contents of one variable under different names. They are not like C pointers and are not aliases for the symbol table. In PHP, the name of a variable and its contents are different things, so one content can have different names. The closest analogy is Unix file names and files — variable names are directory entries, and the contents of variables are the files themselves. Links in PHP are similar to hardlinks in Unix file systems.

Hard links in PHP

A hard link is simply a variable that is synonymous with another variable. Multi-level references (that is, a link to a variable reference, as you can do, for example, in Perl) are not supported. So do not take hard links more seriously than synonyms.
To create a hard link, you need to use the & (ampersand) operator. For example:

$a=10;
$b = &$a; // теперь $b — то же самое, что и $a
$b=0; // на самом деле $a=0
echo "b=$b, a=$a"; // Выводит: "b=0, a=0"

You can refer not only to variables, but also to elements of an array (this makes hard links favorably differ from symbolic ones). For example:

$A=array('a' => 'aaa', 'b' => 'bbb');
$b=&$A['b']; // теперь $b — то же, что и элемент с индексом 'b' массива
$b=0; // на самом деле $A['b']=0;
echo $A['b']; // Выводит 0

However, the array element for which it is planned to create a symbolic link may not exist. As in the following case:

$A=array('a' => 'aaa', 'b' => 'bbb');
$b=&$A['c']; // теперь $b — то же, что и элемент с индексом 'c' массива
echo "Элемент с индексом 'c': (".$A['c'].")";

As a result of the script, although the link $ b was not assigned, a new element with the key c and value - an empty string will be created in the array $ A (we can determine this from the result of echo ). That is, a hard link cannot actually refer to a non-existent object, and if such an attempt is made, then an object is created.

Note : If you remove the line in which the hard link is created, a message will be displayed that the element with the key c is not defined in the array $ A.

Hard links are useful when passing parameters to a user-defined function and returning values ​​from it.

Symbolic links (variable variables)

Symbolic link - this is just a string variable storing the name of another variable (variable). To get to the value of a variable referenced by a symbolic link, you must use the additional $ sign in front of the link name. Consider an example:

$a=10;
$b=20;
$c=30;
$p="a"; // или $p="b" или $p="c" (присваиваем $p имя другой переменной)
echo $$p; // выводит переменную, на которую ссылается $p, т. е. $a
$$p=100; // присваивает $a значение 100

We see that in order to use a regular string variable as a reference, you need to put another $ character in front of it. This tells the interpreter that you should take not the value of $ p itself , but the value of a variable whose name is stored in the $ p variable.

Symbolic links (variables) are used quite rarely.

See also: Variables.

Hard links and custom functions

Passing values ​​by reference

You can pass variables to a user-defined function by reference if you want to allow functions to modify their arguments. In such a case, the user function will be able to change the arguments. The syntax is:

<?php
function foo(&$var)
{
$var++;
}

$a=5;
foo($a);
// $a здесь равно 6
?>

Note that there is no reference sign in the function call - it is only in the function definition. This is enough to correctly pass the arguments by reference.

Another interesting example:

<?php
function funct(&$string)
{
$string .= 'а эта внутри.';
}
$str = 'Эта строка за пределами функции, ';
funct($str);
echo $str; // Выведет 'Эта строка за пределами функции, а эта внутри.'
?>

By reference you can send:

  • Variables like foo ($ a)

  • Operator new, for example foo (new foobar ())

  • References returned by a function, for example:

<?php
function &bar()
{
$a = 5;
return $a;
}
foo(bar());
?>

Any other expression should not be passed by reference, since the result is not defined. For example, the following pass by reference is incorrect:

<?php
function bar() // Операция & отсутствует
{
$a = 5;
return $a;
}
foo(bar());

foo($a = 5); // Выражение, а не переменная
foo(5); // Константа, а не переменная
?>

Return values ​​by reference

Consider another feature of custom PHP functions - return links.

Returning by reference is used when you want to use a function to select a variable with which the reference should be associated. When returning by reference, use the following syntax:

<?php
function &find_var($param)
{
/* ... код ... */
return $found_var;
}

$foo =& find_var($bar);
$foo->x = 2;
?>

This example sets the property of the object returned by the find_var function, and not its copy, as it would be without the use of references.

Another example of returning user-defined function values ​​by reference:

<? php
$ a =   100 ;
/* Далее идет функция, которая возвращает ссылку */
function   & s ()   {
global   $ a ;
// Возвращаем ссылку на переменную $a
return   $ a ;
}
// Присваиваем ссылку переменной $b
$ b =   & s ();
$ b =   0 ;
echo $ a ;   // Выводит 0
?>

Delete links (reset links)

When deleting a link, the link between the name and the content of the variable is simply broken. This does not mean that the contents of the variable will be destroyed. For example:

<?php
$a = 1;
$b =& $a;
unset($a);
?>

This code does not reset $ b , but only $ a .

And yet, a hard link is not an absolutely exact synonym for the object to which it refers. The fact is that the Unset () operator, executed for a hard link, does not delete the object to which it refers, but merely breaks the link between the link and the object.

So, the hard link and the variable (object) to which it refers are completely equal, but changing one entails changing the other. The Unset () operator breaks the link between the object and the link, but the object is deleted only when no one references it anymore.

Again, you can draw an analogy with the call unlink (in Unix).


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)