php5| Object | problem
In the PHP4 era, object references were implemented through a simple "&" notation.
In php5 ($obj 1 = $obj 2;) The default is to refer to the way, do not need to deliberately add a "&" symbol, but in the php5 still retain php4 species
This is used in a reference way.
But what is the difference between these two ways, let's take a look at the analysis below.
The old way of referencing is implemented as follows (the following code can run on PHP4 and PHP5):
Code 1:
Class test{function Get () {return "AAAAA";}}
$t 1 = new test ();
$t 2 = & $t 1;
echo $t 1->get ().
";
echo $t 2->get ().
";
?>
Such variables $t 1 and $t 2 point to the same object, and they share the same object in memory.
Code 2:
Class test{function Get () {return "AAAAA";}}
$t 1 = new test ();
$t 2 = & $t 1;
Unset ($t 1);
Echo ($t 1===null)? "T1 is null.
': ' T1 is not null.
";
echo $t 2->get ().
";
?>
After the T1 variable is unset, T1 becomes null, but T2 still points to the original object.
Code 3:
Class test{function Get () {return "AAAAA";}}
$t 1 = new test ();
$t 2 = & $t 1;
$t 1 = null;
Echo ($t 1===null)? "T1 is null.
': ' T1 is not null.
";
Echo ($t 1===null)? "T2 is null.
': ' T2 is not null.
";
?>
After t1=null, T1 became null, but T2 turned out to be null.
God, how could the results of T1 and T2 be different? Toss for a long time to understand, through the "&" reference to the way, in fact, should not be called "reference", should be called "access", the concept of communication in C language is very clear, and the way the code is written very similar. At the beginning, I thought it was the same way as the object reference in Java, and it was stupid ...... Ah!.
Let's take a look at the way the PHP5 is quoted.
Code 4:
Class test1{
Public Function aa () {
echo "Aaaaaaaaaaa
";
}
Public Function __destruct () {
echo "Game over!";
}
}
$t 1 = new test1 ();
$t 2 = $t 1;
$t 1 = null;
echo $t 2->aa ();
Unset ($t 2);
?>
Code 5:
Class test1{
Public Function aa () {
echo "Aaaaaaaaaaa
";
}
Public Function __destruct () {
echo "Game over!";
}
}
$t 1 = new test1 ();
$t 2 = $t 1;
Unset ($t 1);
echo $t 2->aa ();
Unset ($t 2);
?>
Found no, code 4 and code 5 ran exactly the same results, and the result was satisfactory, and the Java object reference was implemented in the same way.
--------------------------------------------------
conclusion, the result proves that the "&" method of PhP4 is "php5", and the default way is "reference" (nagging batch).
When referencing an object in PHP5, choose the appropriate reference based on the actual situation. If the program is larger, the number of references to the same object is more, and you want to use the object to remove it manually, personal advice to use the "&" mode, and then clear the $var=null. At other times, use the PHP5 default method. In addition, in PHP5 for large array of transmission, the proposed "&" mode, after all, save memory space use.