在 PHP 中使用带有动态变量名的大括号

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

Using braces with dynamic variable names in PHP

phpvariablesdynamicdynamic-variables

提问by user1159454

I'm trying to use dynamic variable names (I'm not sure what they're actually called) But pretty much like this:

我正在尝试使用动态变量名称(我不确定它们的实际名称)但非常像这样:

for($i=0; $i<=2; $i++) {
    $("file" . $i) = file($filelist[$i]);
}

var_dump($file0);

The return is nullwhich tells me it's not working. I have no idea what the syntax or the technique I'm looking for is here, which makes it hard to research. $filelistis defined earlier on.

回报是null告诉我它不起作用。我不知道我在这里寻找的语法或技术是什么,这使得研究变得困难。$filelist之前定义过。

回答by Sarfraz

Wrap them in {}:

将它们包裹起来{}

${"file" . $i} = file($filelist[$i]);

Working Example

工作示例



Using ${}is a way to create dynamic variables, simple example:

using${}是一种创建动态变量的方法,简单的例子:

${'a' . 'b'} = 'hello there';
echo $ab; // hello there

回答by John Slegers

Overview

概述

In PHP, you can just put an extra $in front of a variable to make it a dynamic variable :

在 PHP 中,您可以$在变量前添加一个额外的变量,使其成为动态变量:

$$variableName = $value;

While I wouldn't recommend it, you could even chain this behavior :

虽然我不推荐它,但您甚至可以将这种行为链接起来:

$$$$$$$$DoNotTryThisAtHomeKids = $value;

You can but are not forced to put $variableNamebetween {}:

您可以但不必被迫$variableName介于{}以下内容之间:

${$variableName} = $value;

Using {}is only mandatory when the name of your variable is itself a composition of multiple values, like this :

{}仅当变量的名称本身是多个值的组合时才强制使用,如下所示:

${$variableNamePart1 . $variableNamePart2} = $value;

It is nevertheless recommended to always use {}, because it's more readable.

尽管如此,还是建议始终使用{},因为它更具可读性。

Differences between PHP5 and PHP7

PHP5和PHP7的区别

Another reason to always use {}, is that PHP5 and PHP7 have a slightly different way of dealing with dynamic variables, which results in a different outcome in some cases.

另一个始终使用{}, 的原因是 PHP5 和 PHP7 处理动态变量的方式略有不同,这在某些情况下会导致不同的结果。

In PHP7, dynamic variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the mix of special cases in PHP5. The examples below show how the order of evaluation has changed.

在 PHP7 中,动态变量、属性和方法现在将严格按照从左到右的顺序进行评估,而不是在 PHP5 中混合特殊情况。下面的示例显示了评估顺序是如何变化的。

Case 1 : $$foo['bar']['baz']

情况1 : $$foo['bar']['baz']

  • PHP5 interpetation : ${$foo['bar']['baz']}
  • PHP7 interpetation : ${$foo}['bar']['baz']
  • PHP5 解释: ${$foo['bar']['baz']}
  • PHP7解释: ${$foo}['bar']['baz']

Case 2 : $foo->$bar['baz']

案例2: $foo->$bar['baz']

  • PHP5 interpetation : $foo->{$bar['baz']}
  • PHP7 interpetation : $foo->{$bar}['baz']
  • PHP5 解释: $foo->{$bar['baz']}
  • PHP7解释: $foo->{$bar}['baz']

Case 3 : $foo->$bar['baz']()

案例3: $foo->$bar['baz']()

  • PHP5 interpetation : $foo->{$bar['baz']}()
  • PHP7 interpetation : $foo->{$bar}['baz']()
  • PHP5 解释: $foo->{$bar['baz']}()
  • PHP7解释: $foo->{$bar}['baz']()

Case 4 : Foo::$bar['baz']()

案例4: Foo::$bar['baz']()

  • PHP5 interpetation : Foo::{$bar['baz']}()
  • PHP7 interpetation : Foo::{$bar}['baz']()
  • PHP5 解释: Foo::{$bar['baz']}()
  • PHP7解释: Foo::{$bar}['baz']()

回答by Joakim Johansson

Try using {}instead of ():

尝试使用{}代替()

${"file".$i} = file($filelist[$i]);

回答by Tom

I do this quite often on results returned from a query..

我经常对查询返回的结果执行此操作。

e.g.

例如

// $MyQueryResult is an array of results from a query

foreach ($MyQueryResult as $key=>$value)
{
   ${$key}=$value;
}

Now I can just use $MyFieldname (which is easier in echo statements etc) rather than $MyQueryResult['MyFieldname']

现在我可以只使用 $MyFieldname (在 echo 语句等中更容易)而不是 $MyQueryResult['MyFieldname']

Yep, it's probably lazy, but I've never had any problems.

是的,它可能是懒惰的,但我从来没有遇到任何问题。

回答by corysus

Tom if you have existing array you can convert that array to object and use it like this:

Tom 如果您有现有数组,则可以将该数组转换为对象并像这样使用它:

$r = (object) $MyQueryResult;
echo $r->key;

回答by Murad

i have a solution for dynamically created variable value and combined all value in a variable.

我有一个动态创建的变量值的解决方案,并将所有值组合到一个变量中。

if($_SERVER['REQUEST_METHOD']=='POST'){
    $r=0;
    for($i=1; $i<=4; $i++){
        $a = $_POST['a'.$i];
        $r .= $a;
    }
    echo $r;
}

回答by M61Vulcan

I was in a position where I had 6 identical arrays and I needed to pick the right one depending on another variable and then assign values to it. In the case shown here $comp_cat was 'a' so I needed to pick my 'a' array ( I also of course had 'b' to 'f' arrays)

我所处的位置有 6 个相同的数组,我需要根据另一个变量选择正确的数组,然后为其赋值。在此处显示的情况下 $comp_cat 是 'a' 所以我需要选择我的 'a' 数组(我当然也有 'b' 到 'f' 数组)

Note that the values for the position of the variable in the array go after the closing brace.

请注意,数组中变量位置的值位于右大括号之后。

${'comp_cat_'.$comp_cat.'_arr'}[1][0] = "FRED BLOGGS";

${'comp_cat_'.$comp_cat.'_arr'}[1][1] = $file_tidy;

echo 'First array value is '.$comp_cat_a_arr[1][0].' and the second value is .$comp_cat_a_arr[1][1];

${'comp_cat_'.$comp_cat.'_arr'}[1][0] = "FRED BLOGGS";

${'comp_cat_'.$comp_cat.'_arr'}[1][1] = $file_tidy;

echo '第一个数组值是'.$comp_cat_a_arr[1][0]。' 第二个值是 .$comp_cat_a_arr[1][1];

回答by Vildan Bina

Try using {} instead of ():

尝试使用 {} 代替 ():

${"file".$i} = file($filelist[$i]);