php 一次为多个变量分配相同的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11651594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assign same value to multiple variables at once?
提问by user983248
How can I assign the same value for multiple variables in PHP at once ?
如何一次为 PHP 中的多个变量分配相同的值?
I have something like:
我有类似的东西:
$var_a = 'A';
$var_b = 'A';
$same_var = 'A';
$var_d = 'A';
$some_var ='A';
In my case, I can't rename all variables to have the same name (that would make things more easy), so is there any way to assign the same value to all variables in a much more compact way?
就我而言,我无法将所有变量重命名为具有相同名称(这会使事情变得更容易),那么有没有办法以更紧凑的方式为所有变量分配相同的值?
回答by Tim Cooper
$var_a = $var_b = $same_var = $var_d = $some_var = 'A';
回答by Xeuron
To add to the other answer.
添加到另一个答案。
$a = $b = $c = $dactually means $a = ( $b = ( $c = $d ) )
$a = $b = $c = $d实际上是指 $a = ( $b = ( $c = $d ) )
PHP passes primitive types int, string, etc.by value and objects by reference by default.
PHP默认int, string, etc.按值传递原始类型,按引用传递对象。
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.
但是,您也可以使用关键字按值传递对象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
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.

