同时为多个变量赋值?

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

我有这样的东西:

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

在我的例子中,我不能将所有变量重命名为相同的名称(这样会使事情变得更容易) ,所以有没有办法以更紧凑的方式将相同的值赋给所有变量?

76744 次浏览
$var_a = $var_b = $same_var = $var_d = $some_var = 'A';

补充另一个答案。

$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.