Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are multiple variable assignments done by value or reference?

$a = $b = 0; 

In the above code, are both $a and $b assigned the value of 0, or is $a just referencing $b?

like image 356
Evil Elf Avatar asked Jun 06 '11 19:06

Evil Elf


People also ask

How multiple variables are are assigned?

You can assign multiple values to multiple variables by separating variables and values with commas , . You can assign to more than three variables. It is also possible to assign to different types. If there is one variable on the left side, it is assigned as a tuple.

How are variable assignments done in Python?

In Python, variables need not be declared or defined in advance, as is the case in many other programming languages. To create a variable, you just assign it a value and then start using it. Assignment is done with a single equals sign ( = ).

What is multiple variable assignment in Python?

Python assigns values from right to left. When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should to the right of the assignment operator.


2 Answers

With raw types this is a copy.

test.php

$a = $b = 0;  $b = 3;   var_dump($a); var_dump($b); 

Output:

int(0)  int(3) 

With objects though, that is another story (PHP 5)

test.php

class Obj {      public $_name; }  $a = $b = new Obj();  $b->_name = 'steve';  var_dump($a); var_dump($b); 

Output

object(Obj)#1 (1) { ["_name"]=> string(5) "steve" }  object(Obj)#1 (1) { ["_name"]=> string(5) "steve" } 
like image 117
Bob_Gneu Avatar answered Oct 11 '22 19:10

Bob_Gneu


Regard this code as:

$a = ($b = 0); 

The expression $b = 0 not only assigns 0 to $b, but it yields a result as well. That result is the right part of the assignment, or simply the value that $b got assigned to.

So, $a gets assigned 0 as well.

like image 37
Blagovest Buyukliev Avatar answered Oct 11 '22 18:10

Blagovest Buyukliev