$a = $b = 0;
In the above code, are both $a
and $b
assigned the value of 0
, or is $a
just referencing $b
?
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.
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 ( = ).
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.
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" }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With