PHP - 动态访问变量

时间:2016-02-14 18:46:25

标签: php

在PHP中,是否有办法根据其他因素更改正在更改的变量。例如:

$str1 = "The string is 1";
$str2 = "The string is 2";
$str3 = "The string is 3";
$X = 3;
echo $strX;

>> "The string is 3."

编辑:谢谢,这正是我所需要的:)

2 个答案:

答案 0 :(得分:5)

<?php
$str1 = "The string is 1";
$str2 = "The string is 2";
$str3 = "The string is 3";
$X = 3;
echo ${"str".$X};
?>

在此处阅读更多内容Variable variables

答案 1 :(得分:3)

我认为你在寻找

  $str1 = "The string is 1";
  $str2 = "The string is 2";
  $str3 = "The string is 3";
  $X = "str2";
  echo ${$X};

您也可以使用

   $str1 = "The string is 1";
   $str2 = "The string is 2";
   $str3 = "The string is 3";
   $X = "2";
   echo ${"str".$X};