<p>Are PHP variables passed by value or by reference?</p>

[{'answer_id': 880, 'author': 'Karl Seguin', 'author_id': 34, 'author_profile': 'https://Stackoverflow.com/users/34', 'pm_score': -1, 'selected': False, 'text': '<p>Depends on the version, 4 is by value, 5 is by reference.</p>\n'}, {'answer_id': 881, 'author': 'cmcculloh', 'author_id': 58, 'author_profile': 'https://Stackoverflow.com/users/58', 'pm_score': 5, 'selected': False, 'text': "<p>PHP variables are assigned by value, passed to functions by value and when containing/representing objects are passed by reference. You can force variables to pass by reference using an '&amp;'.</p>\n<p>Assigned by value/reference example:</p>\n<pre><code>$var1 = &quot;test&quot;;\n$var2 = $var1;\n$var2 = &quot;new test&quot;;\n$var3 = &amp;$var2;\n$var3 = &quot;final test&quot;;\n\nprint (&quot;var1: $var1, var2: $var2, var3: $var3);\n</code></pre>\n<p>output:</p>\n<blockquote>\n<p>var1: test, var2: final test, var3: final test</p>\n</blockquote>\n<p>Passed by value/reference example:</p>\n<pre><code>$var1 = &quot;foo&quot;;\n$var2 = &quot;bar&quot;;\n\nchangeThem($var1, $var2);\n\nprint &quot;var1: $var1, var2: $var2&quot;;\n\nfunction changeThem($var1, &amp;$var2){\n    $var1 = &quot;FOO&quot;;\n    $var2 = &quot;BAR&quot;;\n}\n</code></pre>\n<p>output:</p>\n<blockquote>\n<p>var1: foo, var2 BAR</p>\n</blockquote>\n<p>Object variables passed by reference example:</p>\n<pre><code>class Foo{\n    public $var1;\n\n    function __construct(){\n        $this-&gt;var1 = &quot;foo&quot;;\n    }\n\n    public function printFoo(){\n        print $this-&gt;var1;\n    }\n}\n\n\n$foo = new Foo();\n\nchangeFoo($foo);\n\n$foo-&gt;printFoo();\n\nfunction changeFoo($foo){\n    $foo-&gt;var1 = &quot;FOO&quot;;\n}\n</code></pre>\n<p>output:</p>\n<blockquote>\n<p>FOO</p>\n</blockquote>\n<p>(The last example could be better probably.)</p>\n"}, {'answer_id': 885, 'author': 'Michael Stum', 'author_id': 91, 'author_profile': 'https://Stackoverflow.com/users/91', 'pm_score': 10, 'selected': True, 'text': '<p>It\'s by value according to the <a href="http://php.net/manual/en/functions.arguments.php" rel="noreferrer">PHP Documentation</a>.</p>\n\n<blockquote>\n  <p>By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.</p>\n  \n  <p>To have an argument to a function always passed by reference, prepend an ampersand (<strong>&amp;</strong>) to the argument name in the function definition.</p>\n</blockquote>\n\n<pre><code>&lt;?php\nfunction add_some_extra(&amp;$string)\n{\n    $string .= \'and something extra.\';\n}\n\n$str = \'This is a string, \';\nadd_some_extra($str);\necho $str;    // outputs \'This is a string, and something extra.\'\n?&gt;\n</code></pre>\n'}, {'answer_id': 896, 'author': 'Karl Seguin', 'author_id': 34, 'author_profile': 'https://Stackoverflow.com/users/34', 'pm_score': 5, 'selected': False, 'text': '<p><a href="http://www.php.net/manual/en/migration5.oop.php" rel="noreferrer">http://www.php.net/manual/en/migration5.oop.php</a></p>\n\n<blockquote>\n  <p>In PHP 5 there is a new Object Model. PHP\'s handling of objects has been completely rewritten, allowing for better performance and more features. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object\'s identifier).</p>\n</blockquote>\n'}, {'answer_id': 897, 'author': 'Polsonby', 'author_id': 137, 'author_profile': 'https://Stackoverflow.com/users/137', 'pm_score': 3, 'selected': False, 'text': '<p>Variables containing primitive types are passed by value in PHP5. Variables containing objects are passed by reference. There\'s quite an interesting article from Linux Journal from 2006 which mentions this and other OO differences between 4 and 5.</p>\n\n<p><a href="http://www.linuxjournal.com/article/9170" rel="noreferrer">http://www.linuxjournal.com/article/9170</a></p>\n'}, {'answer_id': 7483, 'author': 'grom', 'author_id': 486, 'author_profile': 'https://Stackoverflow.com/users/486', 'pm_score': 6, 'selected': False, 'text': '<p>It seems a lot of people get confused by the way objects are passed to functions and what passing by reference means. Object are still passed by value, it\'s just the value that is passed in PHP5 is a reference handle. As proof:</p>\n<pre><code>&lt;?php\nclass Holder {\n    private $value;\n\n    public function __construct($value) {\n        $this-&gt;value = $value;\n    }\n\n    public function getValue() {\n        return $this-&gt;value;\n    }\n}\n\nfunction swap($x, $y) {\n    $tmp = $x;\n    $x = $y;\n    $y = $tmp;\n}\n\n$a = new Holder(\'a\');\n$b = new Holder(\'b\');\nswap($a, $b);\n\necho $a-&gt;getValue() . &quot;, &quot; . $b-&gt;getValue() . &quot;\\n&quot;;\n</code></pre>\n<p>Outputs:</p>\n<pre><code>a, b\n</code></pre>\n<p>To <a href="http://en.wikipedia.org/wiki/Pass_by_reference#Call_by_reference" rel="nofollow noreferrer">pass by reference</a> means we can modify the variables that are seen by the caller, which clearly the code above does not do. We need to change the swap function to:</p>\n<pre><code>&lt;?php\nfunction swap(&amp;$x, &amp;$y) {\n    $tmp = $x;\n    $x = $y;\n    $y = $tmp;\n}\n\n$a = new Holder(\'a\');\n$b = new Holder(\'b\');\nswap($a, $b);\n\necho $a-&gt;getValue() . &quot;, &quot; . $b-&gt;getValue() . &quot;\\n&quot;;\n</code></pre>\n<p>Outputs:</p>\n<pre><code>b, a\n</code></pre>\n<p>in order to pass by reference.</p>\n'}, {'answer_id': 574631, 'author': 'Bingy', 'author_id': 69518, 'author_profile': 'https://Stackoverflow.com/users/69518', 'pm_score': 3, 'selected': False, 'text': "<p>You can do it either way.</p>\n<p>Put an '&amp;' symbol in front and the variable you are passing becomes one and the same as its origin i.e. you can pass by reference, rather than make a copy of it.</p>\n<p>so</p>\n<pre><code>    $fred = 5;\n    $larry = &amp; $fred;\n    $larry = 8;\n    echo $fred;//this will output 8, as larry and fred are now the same reference.\n</code></pre>\n"}, {'answer_id': 2034022, 'author': 'Miha', 'author_id': 247128, 'author_profile': 'https://Stackoverflow.com/users/247128', 'pm_score': 1, 'selected': False, 'text': '<p>Objects are passed by reference in PHP 5 and by value in PHP 4.\nVariables are passed by value by default!</p>\n\n<p>Read here: <a href="http://www.webeks.net/programming/php/ampersand-operator-used-for-assigning-reference.html" rel="nofollow noreferrer">http://www.webeks.net/programming/php/ampersand-operator-used-for-assigning-reference.html</a></p>\n'}, {'answer_id': 2812176, 'author': 'Ricardo Saracino', 'author_id': 338456, 'author_profile': 'https://Stackoverflow.com/users/338456', 'pm_score': 1, 'selected': False, 'text': '<pre><code>class Holder\n{\n    private $value;\n\n    public function __construct( $value )\n    {\n        $this-&gt;value = $value;\n    }\n\n    public function getValue()\n    {\n        return $this-&gt;value;\n    }\n\n    public function setValue( $value )\n    {\n        return $this-&gt;value = $value;\n    }\n}\n\nclass Swap\n{       \n    public function SwapObjects( Holder $x, Holder $y )\n    {\n        $tmp = $x;\n\n        $x = $y;\n\n        $y = $tmp;\n    }\n\n    public function SwapValues( Holder $x, Holder $y )\n    {\n        $tmp = $x-&gt;getValue();\n\n        $x-&gt;setValue($y-&gt;getValue());\n\n        $y-&gt;setValue($tmp);\n    }\n}\n\n\n$a1 = new Holder(\'a\');\n\n$b1 = new Holder(\'b\');\n\n\n\n$a2 = new Holder(\'a\');\n\n$b2 = new Holder(\'b\');\n\n\nSwap::SwapValues($a1, $b1);\n\nSwap::SwapObjects($a2, $b2);\n\n\n\necho \'SwapValues: \' . $a2-&gt;getValue() . ", " . $b2-&gt;getValue() . "&lt;br&gt;";\n\necho \'SwapObjects: \' . $a1-&gt;getValue() . ", " . $b1-&gt;getValue() . "&lt;br&gt;";\n</code></pre>\n\n<p>Attributes are still modifiable when not passed by reference so beware.</p>\n\n<p>Output:</p>\n\n<p>SwapObjects: b, a\nSwapValues: a, b</p>\n'}, {'answer_id': 9696799, 'author': 'hardik', 'author_id': 805437, 'author_profile': 'https://Stackoverflow.com/users/805437', 'pm_score': 7, 'selected': False, 'text': '<p>In PHP, by default, objects are passed as reference to a new object.</p>\n<p>See this example:</p>\n<pre><code>class X {\n  var $abc = 10; \n}\n\nclass Y {\n\n  var $abc = 20; \n  function changeValue($obj)\n  {\n   $obj-&gt;abc = 30;\n  }\n}\n\n$x = new X();\n$y = new Y();\n\necho $x-&gt;abc; //outputs 10\n$y-&gt;changeValue($x);\necho $x-&gt;abc; //outputs 30\n</code></pre>\n<p>Now see this:</p>\n<pre><code>class X {\n  var $abc = 10; \n}\n\nclass Y {\n\n  var $abc = 20; \n  function changeValue($obj)\n  {\n    $obj = new Y();\n  }\n}\n\n$x = new X();\n$y = new Y();\n\necho $x-&gt;abc; //outputs 10\n$y-&gt;changeValue($x);\necho $x-&gt;abc; //outputs 10 not 20 same as java does.\n</code></pre>\n<p>Now see this:</p>\n<pre><code>class X {\n  var $abc = 10; \n}\n\nclass Y {\n\n  var $abc = 20; \n  function changeValue(&amp;$obj)\n  {\n    $obj = new Y();\n  }\n}\n\n$x = new X();\n$y = new Y();\n\necho $x-&gt;abc; //outputs 10\n$y-&gt;changeValue($x);\necho $x-&gt;abc; //outputs 20 not possible in java.\n</code></pre>\n<p>I hope you can understand this.</p>\n'}, {'answer_id': 27588152, 'author': 'Mahsin', 'author_id': 3699965, 'author_profile': 'https://Stackoverflow.com/users/3699965', 'pm_score': 3, 'selected': False, 'text': '<p>You can pass a variable to a function by reference. This function will be able to modify the original variable.</p>\n\n<p>You can define the passage by reference in the function definition:</p>\n\n<pre><code>&lt;?php\nfunction changeValue(&amp;$var)\n{\n    $var++;\n}\n\n$result=5;\nchangeValue($result);\n\necho $result; // $result is 6 here\n?&gt;\n</code></pre>\n'}, {'answer_id': 31429088, 'author': 'atif', 'author_id': 5027344, 'author_profile': 'https://Stackoverflow.com/users/5027344', 'pm_score': 0, 'selected': False, 'text': "<p>Actually both methods are valid but it depends upon your requirement. Passing values by reference often makes your script slow. So it's better to pass variables by value considering time of execution. Also the code flow is more consistent when you pass variables by value.</p>\n"}, {'answer_id': 49587783, 'author': 'PPL', 'author_id': 9411789, 'author_profile': 'https://Stackoverflow.com/users/9411789', 'pm_score': 0, 'selected': False, 'text': '<p>Use this for functions when you wish to simply alter the original variable and return it again to the same variable name with its new value assigned.</p>\n\n<pre><code>function add(&amp;$var){ // The &amp;amp; is before the argument $var\n   $var++;\n}\n$a = 1;\n$b = 10;\nadd($a);\necho "a is $a,";\nadd($b);\necho " a is $a, and b is $b"; // Note: $a and $b are NOT referenced\n</code></pre>\n'}, {'answer_id': 60082753, 'author': 'AleksandrH', 'author_id': 5323344, 'author_profile': 'https://Stackoverflow.com/users/5323344', 'pm_score': 3, 'selected': False, 'text': '<p><strong>TL;DR</strong>: PHP supports both pass by value and pass by reference. References are declared using an ampersand (<code>&amp;</code>); this is very similar to how C++ does it. When the formal parameter of a function is not declared with an ampersand (i.e., it\'s not a reference), <strong>everything</strong> is passed by value, including objects. There is no distinction between how objects and primitives are passed around. The key is to understand <em>what</em> gets passed along when you pass in objects to a function. This is where understanding pointers is invaluable.</p>\n<p>For anyone who comes across this in the future, I want to share this gem from the <a href="https://www.php.net/manual/en/language.oop5.references.php" rel="nofollow noreferrer">PHP docs, posted by an anonymous user</a>:</p>\n<blockquote>\n<p>There seems to be some confusion here. The distinction between pointers and references is not particularly helpful.\nThe behavior in some of the &quot;comprehensive&quot; examples already posted can be explained in simpler unifying terms. Hayley\'s code, for example, is doing EXACTLY what you should expect it should. (Using &gt;= 5.3)</p>\n</blockquote>\n<blockquote>\n<p>First principle:\nA pointer stores a memory address to access an object. Any time an object is assigned, a pointer is generated. (I haven\'t delved TOO deeply into the Zend engine yet, but as far as I can see, this applies)</p>\n</blockquote>\n<blockquote>\n<p>2nd principle, and source of the most confusion:\nPassing a variable to a function is done by default as a value pass, ie, you are working with a copy. &quot;But objects are passed by reference!&quot; A common misconception both here and in the Java world. I never said a copy OF WHAT. The default passing is done by value. Always. WHAT is being copied and passed, however, is the pointer. When using the &quot;-&gt;&quot;, you will of course be accessing the same internals as the original variable in the caller function. Just using &quot;=&quot; will only play with copies.</p>\n</blockquote>\n<blockquote>\n<p>3rd principle:\n&quot;&amp;&quot; automatically and permanently sets another variable name/pointer to the same memory address as something else until you decouple them. It is correct to use the term &quot;alias&quot; here. Think of it as joining two pointers at the hip until forcibly separated with &quot;unset()&quot;. This functionality exists both in the same scope and when an argument is passed to a function. Often the passed argument is called a &quot;reference,&quot; due to certain distinctions between &quot;passing by value&quot; and &quot;passing by reference&quot; that were clearer in C and C++.</p>\n</blockquote>\n<blockquote>\n<p>Just remember: pointers to objects, not objects themselves, are passed to functions. These pointers are COPIES of the original unless you use &quot;&amp;&quot; in your parameter list to actually pass the originals. Only when you dig into the internals of an object will the originals change.</p>\n</blockquote>\n<p>And here\'s the example they provide:</p>\n<pre class="lang-php prettyprint-override"><code>&lt;?php\n\n//The two are meant to be the same\n$a = &quot;Clark Kent&quot;; //a==Clark Kent\n$b = &amp;$a; //The two will now share the same fate.\n\n$b=&quot;Superman&quot;; // $a==&quot;Superman&quot; too.\necho $a;\necho $a=&quot;Clark Kent&quot;; // $b==&quot;Clark Kent&quot; too.\nunset($b); // $b divorced from $a\n$b=&quot;Bizarro&quot;;\necho $a; // $a==&quot;Clark Kent&quot; still, since $b is a free agent pointer now.\n\n//The two are NOT meant to be the same.\n$c=&quot;King&quot;;\n$d=&quot;Pretender to the Throne&quot;;\necho $c.&quot;\\n&quot;; // $c==&quot;King&quot;\necho $d.&quot;\\n&quot;; // $d==&quot;Pretender to the Throne&quot;\nswapByValue($c, $d);\necho $c.&quot;\\n&quot;; // $c==&quot;King&quot;\necho $d.&quot;\\n&quot;; // $d==&quot;Pretender to the Throne&quot;\nswapByRef($c, $d);\necho $c.&quot;\\n&quot;; // $c==&quot;Pretender to the Throne&quot;\necho $d.&quot;\\n&quot;; // $d==&quot;King&quot;\n\nfunction swapByValue($x, $y){\n$temp=$x;\n$x=$y;\n$y=$temp;\n//All this beautiful work will disappear\n//because it was done on COPIES of pointers.\n//The originals pointers still point as they did.\n}\n\nfunction swapByRef(&amp;$x, &amp;$y){\n$temp=$x;\n$x=$y;\n$y=$temp;\n//Note the parameter list: now we switched \'em REAL good.\n}\n\n?&gt;\n</code></pre>\n<p><a href="https://www.aleksandrhovhannisyan.com/blog/javascript-pass-by-reference/" rel="nofollow noreferrer">I wrote an extensive, detailed blog post on this subject for JavaScript</a>, but I believe it applies equally well to PHP, C++, and any other language where people seem to be confused about pass by value vs. pass by reference.</p>\n<p>Clearly, PHP, like C++, is a language that does support pass by reference. By default, objects are passed by value. When working with variables that store objects, it helps to see those variables as pointers (because that is fundamentally what they are, at the assembly level). If you pass a pointer by value, you can still &quot;trace&quot; the pointer and modify the properties of the object being pointed to. What you cannot do is have it point to a different object. Only if you explicitly declare a parameter as being passed by reference will you be able to do that.</p>\n'}, {'answer_id': 67052160, 'author': 'CGeorgian', 'author_id': 4195727, 'author_profile': 'https://Stackoverflow.com/users/4195727', 'pm_score': 1, 'selected': False, 'text': "<p>Regarding how objects are passed to functions you still need to understand that without &quot;&amp;&quot;, you pass to the function an object handle , object handle that is still passed by value , and it contains the value of a pointer. But you can not change this pointer until you pass it by reference using the &quot;&amp;&quot;</p>\n<pre><code>&lt;?php\n        class Example \n        {\n            public $value;\n         \n        }\n        \n        function test1($x) \n        {\n             //let's say $x is 0x34313131\n             $x-&gt;value = 1;  //will reflect outsite of this function\n                             //php use pointer 0x34313131 and search for the \n                             //address of 'value' and change it to 1\n\n        }\n        \n        function test2($x) \n        {\n             //$x is 0x34313131\n             $x = new Example;\n             //now $x is 0x88888888\n             //this will NOT reflect outside of this function \n             //you need to rewrite it as &quot;test2(&amp;$x)&quot;\n             $x-&gt;value = 1000; //this is 1000 JUST inside this function\n                 \n        \n        }\n         \n     $example = new Example;\n    \n     $example-&gt;value = 0;\n    \n     test1($example); // $example-&gt;value changed to  1\n    \n     test2($example); // $example did NOT changed to a new object \n                      // $example-&gt;value is still 1\n     \n ?&gt;\n</code></pre>\n"}, {'answer_id': 68130959, 'author': 'HSLM', 'author_id': 2763028, 'author_profile': 'https://Stackoverflow.com/users/2763028', 'pm_score': 0, 'selected': False, 'text': '<p>A PHP reference is an alias, allowing two different variables to write to the same value.</p>\n<p>And in PHP, if you have a variable that contains an object, that variable does not contain the object itself. Instead, it contains an identifier for that object. The object accessor will use the identifier to find the actual object. So when we use the object as an argument in function or assign it to another variable, we will be copying the identifier that points to the object itself.</p>\n<p><a href="https://hsalem.com/posts/you-think-you-know-php.html" rel="nofollow noreferrer">https://hsalem.com/posts/you-think-you-know-php.html</a></p>\n<pre><code>class Type {}\n\n$x = new Type();\n$y = $x;\n$y = &quot;New value&quot;;\n\nvar_dump($x); // Will print the object.\nvar_dump($y); // Will print the &quot;New value&quot;\n\n$z = &amp;$x; // $z is a reference of $x\n\n$z = &quot;New value&quot;;\nvar_dump($x); // Will print &quot;New value&quot;\nvar_dump($z); // Will print &quot;New value&quot;\n\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/879', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/58/']