Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

=& operator, memories

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.....

like image 969
Micah Avatar asked Apr 27 '26 06:04

Micah


1 Answers

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.

like image 78
Fabian Schmengler Avatar answered Apr 28 '26 21:04

Fabian Schmengler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!