同时初始化多个 PHP 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9651793/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:22:19  来源:igfitidea点击:

Initializing Multiple PHP Variables Simultaneously

php

提问by dreamer_999

How may I initialize multiple PHP variables with a value of zero simultaneously without using an array? I wish to write code that is essentially equivalent to the following:

如何在不使用数组的情况下同时零值初始化多个 PHP 变量?我希望编写的代码基本上等同于以下内容:

$first = 0;
$second = 0;
$third = 0;
$fourth = 0;

回答by rid

$first = $second = $third = $fourth = 0;

回答by slevy1

While it is feasible to initialize multiple variables using a comma operator within a for-loop, as follows:

虽然在 for 循环中使用逗号运算符初始化多个变量是可行的,如下所示:

<?php
for ($a=0,$b=0,$c=0,$d=0;;) {
    break;
}
var_dump($a,$b,$c,$d);

(See demo here)

(请参阅此处的演示)

the listconstruct provides a more efficient way to perform multiple variable assignment, as depicted in the following example:

列表构建体提供执行多个变量赋值一个更有效的方式,如在下面的示例中所描绘的:

<?php

list( $first, $second, $third, $fourth ) = array( 0, 0, 0, 0 );
var_dump($first, $second, $third, $fourth );

See demo here

在这里查看演示

One may wish to reconsider avoiding the usage of arrays to achieve multiple initialized variables. With PHP7.1+ one may write simpler, robust code if one utilizes array destructuringavailable with short array syntax, as follows:

人们可能希望重新考虑避免使用数组来实现多个初始化变量。使用 PHP7.1+ 可以编写更简单、健壮的代码,如果使用数组解构和短数组语法,如下所示:

<?php

[$first, $second, $third, $fourth ] = [0, 0, 0, 0];
var_dump($first, $second, $third, $fourth );

See demo here.

在这里查看演示。

If one needs to be certain that the variables being initialized were not previously set, see this related discussion, particularly this response.

如果需要确定被初始化的变量先前未设置,请参阅此相关讨论,尤其是此响应

回答by Yogi Ghorecha

If you want to initialize multiple array variables then use

如果要初始化多个数组变量,请使用

# Initialize multiple array variables with Empty values
$array_1 = $array_2 = $array_3 = array();

# Initialize multiple array variables with Some values in it
list( $array_1, $array_2, $array_3) = array('one','two','three');

# Print value of array variables
var_dump($array_1,$array_2,$array_3);

Output:
*******
string 'one' (length=3)
string 'two' (length=3)
string 'three' (length=5)

If you want to initialize multiple regular variables then use

如果要初始化多个常规变量,请使用

# Initialize multiple regular variables with values
$a = $b = $c = 'Hello PHP';
echo $a.'<br>',$b.'<br>', $c.'<br>';

Output:
*******
Hello PHP
Hello PHP
Hello PHP