如何在变量内插入变量

时间:2013-05-17 11:24:11

标签: php

我有php代码:

$rand = rand(1,5);

我想定义具有rand函数名称的var,如:

$$rand // if $rand= 1 then the var will be $1

然后再做

switch($rand){
case(1):
$$rand = 'How many legs dog has ?';
$ans= '4';      }

该代码用于定义安全问题。 希望有人得到我的想法。我该怎么办?

3 个答案:

答案 0 :(得分:3)

有时能够拥有变量变量名称很方便。也就是说,一个可以动态设置和使用的变量名。使用如下语句设置普通变量:

<?php
$a = 'hello';
?>

变量变量采用变量的值并将其视为变量的名称。在上面的示例中,hello可以通过使用两个美元符号用作变量的名称。即。

<?php
$$a = 'world';
?>

此时已经定义了两个变量并将其存储在PHP符号树中:$ a包含内容“hello”,$ hello包含内容“world”。因此,这句话:

<?php
echo "$a ${$a}";
?>

产生完全相同的输出:

<?php
echo "$a $hello";
?>

即。他们都产生:你好世界。

为了将变量变量与数组一起使用,您必须解决模糊问题。也就是说,如果你写$$ a [1],那么解析器需要知道你是否想要使用$ a [1]作为变量,或者你想要将$$作为变量,然后是[1]索引来自那个变量。解决这种歧义的语法是:第一种情况为$ {$ a [1]},第二种情况为$ {$ a} [1]。

也可以使用变量属性名访问类属性。变量属性名称将在进行调用的范围内解析。例如,如果你有一个表达式,例如$ foo-&gt; $ bar,那么本地范围将被检查$ bar,它的值将被用作$ foo属性的名称。如果$ bar是数组访问权限,也是如此。

答案 1 :(得分:1)

// Sanitize the arrays
$questions = array();
$answers = array();

// Build some questions and assign to the questions array
$questions[0] = 'How many legs does a dog have?';
$questions[1] = 'How many eyes does a human have?';
$questions[2] = 'How many legs does a spider have?';


// Add the answers, making sure the array index is the same as the questions array
$answers[0] = 4;
$answers[1] = 2;
$answers[2] = 8;


// Select a question to use
$questionId = rand(0, count($questions));


// Output the question and answer
echo 'questions: ' . $questions[$questionId];
echo 'answer: ' . $answers[$questionId];

PHP中的变量不能以数字开头。

答案 2 :(得分:0)

$ {$ rand}是正确的方法。但请注意,您的变量名称不能以数字开头。

引用php manual

  

变量名遵循与PHP中其他标签相同的规则。有效的变量名称以字母或下划线开头,后跟任意数量的字母,数字或下划线。作为正则表达式,它将表达为:'[a-zA-Z_ \ x7f- \ xff] [a-zA-Z0-9_ \ x7f- \ xff] *'