0

如何将动态 var 加入现有 var?

例如:

我的代码:

<?

// Gets value from url. In this example c is 1.

$c = $_GET[c];  

// Multiple static questions will be pulled from a list. 
// I use two as an example below. 

$Q1 = "Is this question one?";
$Q2 = "so this must be question two then?"

echo "$c: ";
echo "Q$c";  // returns "Q1" but not the string above.
echo '$Q.$c"; // returns the val 1

?>

如何将两者结合在一起并让它返回适当的字符串?

4

4 回答 4

4

使用包含多个值的数组代替动态变量名称。

$num = $_GET['c'];

$questions = array(
    "Is this question one?",
    "so this must be question two then?"
);

echo "$num: ";
echo "Q$num";
echo $questions[$num];

有很多很多理由更喜欢数组而不是“变量变量”。一个是循环遍历数组中的所有项目很容易:

foreach ($questions as $num => $question) {
    echo "Q$num: $question\n";
}

另一个是您可以计算数组的大小。

echo "There are " . count($questions) . " total questions.";

另一个是您可以轻松修改它们。有很多很多很多方法来操作数组,而使用变量变量之类的粗糙工具是永远无法做到的。

// Add a new question to the array.
$questions[] = 'Question 3: Who are you?!';

// Remove duplicate questions.
$questions = array_unique($questions);
于 2013-01-05T22:34:27.233 回答
2

看起来你真正要找的是一个数组

$questions = array("Question 0", "Question 1", "Question 2");
$q = 1;
echo $questions[$q]; //"Question 1"

否则,您将不得不使用一些var-var讨厌的 hackiness (不要这样做):

echo ${'Q' . $c};

此外,$_GET[c]应该是$_GET['c']除非c实际上是一个常量(我希望它不是因为它c是一个可怕的常量名称)。你应该使用isset而不是假设c密钥存在于$_GET


完整示例:

$questions = array("Question 0", "Question 1", "Question 2");

$c = (isset($_GET['c'])) ? (int) $_GET['c'] : null;
if (isset($questions[$c])) {
    echo "The question is: " . $questions[$c];
} else {
    echo "The question was not found";
}

您可能还应该意识到短开放标签的缺点。如果服务器禁用了它们,那么您所有的 PHP 代码都会中断。键入 3 个额外字符似乎不值得冒这个风险。(虽然批量查找/替换当然很容易<?-> <?php。)

于 2013-01-05T22:34:09.353 回答
0

我不确定我明白你的意思,但我认为这是答案:

<?php

$var = "Q".$_GET['c'];

echo $$var; // take care of the double dollar sign

?>

但当然更喜欢数组

于 2013-01-05T22:35:00.760 回答
0

你可以像这样使用phpeval()函数:

eval("echo \$Q$c;");

但是您应该注意不要在未经验证的情况下放置用户数据,因为这可能会导致安全问题。

于 2013-01-05T23:02:50.583 回答