在PHP中使用变量变量时遇到问题

时间:2014-04-26 05:37:59

标签: php variables echo

我正在从书中做这个代码,我似乎无法让它工作

<html>
<head> <h3> <u> PHP tutorials  </u> </h3> </head>
<body>

<?php

$Texas = "large";
$RhodeIsland = "small";

$statement = "Texas";
echo "$statement is $($statement)<br>";

$statement = "RhodeIsland";
echo "$statement is $($statement)<br>";

?>
</body>
</html>

这是我不断得到的输出:

德克萨斯州是(德克萨斯州)

RhodeIsland是$(RhodeIsland)

而不是:

德克萨斯州很大

RhodeIsland很小

4 个答案:

答案 0 :(得分:3)

语法为:${$variable_name},而不是$($variable_name)。您需要将代码更改为:

$statement = "Texas";
echo "$statement is ${$statement}<br>";

有关详细信息,请参阅PHP manual documentation on Variable Variables

Demo

答案 1 :(得分:0)

你去了:

 <?php

    $Texas = "large";
    $RhodeIsland = "small";

    $statement = "Texas";
    echo $statement." is ".${$statement}."<br />";

    $statement = "RhodeIsland";
    echo $statement." is ".${$statement} ."<br />";

    ?>

答案 2 :(得分:0)

您应该使用花括号而不是括号。

$statement = "RhodeIsland";
echo "$statement is ${$statement}<br>";

关于这个主题的PHP文档在这里:http://www.php.net/manual/en/language.variables.variable.php

答案 3 :(得分:0)

这有效:)

    <?php
    $Texas = "large";
    $RhodeIsland = "small";

    $statement = "Texas";
    echo $statement." is ".$$statement."<br>";

    $statement = "RhodeIsland";
    echo $statement." is ".$$statement."<br>";