I am very confused about how using & operator to reduce memories.
Can I have an answer for below question??
clase C{
function B(&$a){
$this->a = &$a;
$this->a = $a;
//They are the same here created new variable $this->a??
// Or only $this->a = $a will create new variable?
}
}
$a = 1;
C = new C;
C->B($a)
Or maybe my understanding is totally wrong.....
Never ever use references in PHP just to reduce memory load. PHP handles that perfectly with its internal copy on write mechanism. Example:
$a = str_repeat('x', 100000000); // Memory used ~ 100 MB
$b = $a; // Memory used ~ 100 MB
$b = $b . 'x'; // Memory used ~ 200 MB
You should only use references if you know exactly what you are doing and need them for functionality (and that's almost never, so you could as well just forget about them). PHP references are quirky and can result to some unexpected behaviour.
Value type variables will only be copied when their value changes, if you only assign it in your example it wont be copied, memory footprint will be the same as if u have not used the & operator.
I recommend that you read these articles about passing values by reference:
When to pass-by-reference in PHP
When is it good to use pass by reference in PHP?
http://schlueters.de/blog/archives/125-Do-not-use-PHP-references.html
it is considered a microoptimalization, and hurts the transparency of the code
I am very confused about how using & operator to reduce memories.
If you don't know it, you probably don't need it :) The &
is quite useless nowadays, because of several enhancements in the PHP-core over the last years. Usually you would use &
to avoid, that PHP copies the value to the memory allocated for the second variable, but instead (in short) let both variables point to the same memory.
But nowadays
To sum it up: The benefits of &
already exists as feature of the core, but without the ugly side-effects of the operator