一次将相同的值分配给多个变量?


115

如何一次为PHP中的多个变量分配相同的值?

我有类似的东西:

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

就我而言,我不能将所有变量重命名为相同的名称(这会使事情变得更容易),那么有没有办法以更加紧凑的方式为所有变量分配相同的值?

Answers:


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

精采,对我来说很完美$ level1 = $ level2 = $ level3 = $ level4 = false;
geilt

1
有限制吗?
迪皮邪恶2014年

9
这不能在Php类中使用,这是原始类型。
Chaminda Bandara

@ChamindaBandara你是什么意思不能在PHP类中使用?
Eoin

4
@Eoin:这样做时$var_a = $var_b = ... = new Class();,所有变量都将引用的相同实例Class
蒂姆·库珀

1

添加到其他答案。

$a = $b = $c = $d 实际上意味着 $a = ( $b = ( $c = $d ) )

PHP 默认int, string, etc.通过值传递基本类型,并通过引用传递对象

那意味着

$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

但是,您也可以使用关键字通过值传递对象clone,但必须使用括号。

$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

但是,您不能使用此方法通过带有关键字的引用来传递基本类型&

$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.
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.