5

In PHP, what is the difference between using a pointer such as:

function foo( $var )
{
    $var = 3;
}

$a = 0;
foo( &$a );

And reference:

function foo( &$var )
{
    $var = 3;
}

$a = 0;
foo( $a );

They both modify the value of the original variable, but are they represented differently internally?

Sarathi
  • 1,023
  • 1
  • 14
  • 22
  • 3
    use the second one since the first is no longer supported / available. – luk2302 Jun 29 '13 at 18:59
  • 1
    Yes, they works the same way, this is message from PHP 5.3.8 for the 1st alternative: `Deprecated: Call-time pass-by-reference has been deprecated; If you would like to pass it by reference, modify the declaration of foo(). If you would like to enable call-time pass-by-reference, you can set allow_call_time_pass_reference to true in your INI file in C:\xampp\htdocs\a.php on line 8` – Stano Jun 29 '13 at 19:02

1 Answers1

12

In PHP, there are no pointers, only references. Your examples demonstrate pass by reference

The difference between your code snippets is only in syntax, where the first syntax is now deprecated.

Yogu
  • 9,165
  • 5
  • 37
  • 58
  • Thanks, I wasn't aware they were the same thing or that the first style was deprecated. Also, doesn't passing by reference store a reference to the passed variable in the function argument? If so, how are no references involved? – Sarathi Jun 29 '13 at 19:10
  • Ok, I'm not sure how pass-by-reference is implemented internally. I only think about it differently because many languages have pass-by-reference, but no references as PHP has. But that has nothing to do with your question, so I removed the confosing part. – Yogu Jun 29 '13 at 19:14
  • Is passing by reference a better practice in terms of memory management? – Jomar Sevillejo Oct 24 '16 at 14:57
  • 1
    @JomarSevillejo No, as PHP employs [copy-on-write semantic](https://stackoverflow.com/questions/11074970/will-copy-on-write-prevent-data-duplication-on-arrays), there shouldn't really be a noticable performance difference. – Yogu Nov 08 '16 at 14:07