Assign same value to multiple variables at once? Assign same value to multiple variables at once? php php

Assign same value to multiple variables at once?


$var_a = $var_b = $same_var = $var_d = $some_var = 'A';


To add to the other answer.

$a = $b = $c = $d actually means $a = ( $b = ( $c = $d ) )

PHP passes primitive types int, string, etc. by value and objects by reference by default.

That means

$c = 1234;$a = $b = $c;$c = 5678;//$a and $b = 1234; $c = 5678;$c = new Object();$c->property = 1234;$a = $b = $c;$c->property = 5678;// $a,b,c->property = 5678 because they are all referenced to same variable

However, you CAN pass objects by value too, using keyword clone, but you will have to use parenthesis.

$c = new Object();$c->property = 1234;$a = clone ($b = clone $c);$c->property = 5678;// $a,b->property = 1234; c->property = 5678 because they are cloned

BUT, you CAN NOT pass primitive types by reference with keyword & using this method

$c = 1234;$a = $b = &$c; // no syntax error// $a is passed by value. $b is passed by reference of $c$a = &$b = &$c; // syntax error$a = &($b = &$c); // $b = &$c is okay. // but $a = &(...) is error because you can not pass by reference on value (you need variable)// You will have to do manually$b = &$c;$a = &$b;etc.