About PHP variable for call by value and call reference

I have a question about how PHP handles assignment of variable values.

we have the following statement:

$myVariable = "value";

The above statement assigns a value to a variable $myVariableand then allocates a memory cell to it.

But if we add the following statement to the above script:

$secondVariable = $myVariable;

Then:

As for performance problems, it is recommended to avoid duplication of values ​​and continue to use links if the value is not changed (C ++, Dietel and Dietel, the famous book "How to program in C ++")

But what about PHP? I heard, just heard, that PHP does some tricks and manages such duplications ( $secondVariable = $myVarible) by calling by reference rather than by value, and does not duplicate the variable until some changes happen with $ secondVariable, and after that will be made duplication.

Conclusion:

$myVariable = "value";

$secondVariable = $myVariable;

Something like this in C ++:

string myVariable = "value";

string secondVariable = &myVariable;

Although I know that PHP is written in C, C ++ is a close descendant of C.

Can someone say if the above is correct, and if PHP manages such variables or doesn’t care, and how C&C++does it create a new memory cell each time a value is assigned?

+4
source share
1 answer

This is a little different. You can also use a link pointer in PHP:

$a = &$b ;

$a, $b ( ), , .

:

$a = 'something' ;
$b = $a ;

$b $a. . , $b ( $a), PHP $a. , $a $b, , .

, "memory_get_usage" :

[dcordel:~] master+ ± php /tmp/test-1.php 

$aVar = str_repeat('a', 268435456);
$another = &$aVar ;
Mem : 256 Mo

[dcordel:~] master+ ± php /tmp/test-2.php 
$aVar = str_repeat('a', 268435456);
$another = str_repeat('a', 268435456);
Mem : 512 Mo

[dcordel:~] master+ ± php /tmp/test-3.php     
$aVar = str_repeat('a', 268435456);
$another = $aVar ;
//before
$another.= 'a' ;
//after

before update : Mem : 256 Mo
after update :  Mem : 512 Mo
+3

Source: https://habr.com/ru/post/1547185/


All Articles