Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: making a copy of a reference variable

Tags:

php

If I make a copy of a reference variable. Is the new variable a pointer or does it hold the value of the variable the pointer was referring to?

like image 427
HyderA Avatar asked May 15 '10 12:05

HyderA


People also ask

Does PHP copy by reference?

TL;DR: PHP supports both pass by value and pass by reference. References are declared using an ampersand ( & ); this is very similar to how C++ does it.

How copy data from one variable to another in PHP?

The clone keyword is used to create a copy of an object. If any of the properties was a reference to another variable or object, then only the reference is copied. Objects are always passed by reference, so if the original object has another object in its properties, the copy will point to the same object.

How can you pass a variable by reference in PHP?

For passing variables by reference, it is necessary to add the ampersand ( & ) symbol before the argument of the variable. An example of such a function will look as follows: function( &$x ). The scope of the global and function variables becomes global. The reason is that they are defined by the same reference.

How do you assign the value of a one variable to another variable in PHP reference variable?

In PHP, there is a shortcut for appending a new string to the end of another string. This can be easily done with the string concatenation assignment operator ( . = ). This operator will append the value on its right to the value on its left and then reassign the result to the variable on its left.


2 Answers

It holds the value. If you wanted to point, use the & operator to copy another reference:

$a = 'test';
$b = &$a;
$c = &$b;
like image 195
Delan Azabani Avatar answered Sep 28 '22 08:09

Delan Azabani


Let's make a quick test:

<?php

$base = 'hello';
$ref =& $base;
$copy = $ref;

$copy = 'world';

echo $base;

Output is hello, therefore $copy isn't a reference to %base.

like image 29
Crozin Avatar answered Sep 28 '22 07:09

Crozin