2010-11-02 55 views
3

我想在PHP中建立一个动态变量,尽管在这个问题上已经看到了StackOverflow上的一些问题,我仍然难住...:/如何使用PHP构建动态变量?

变量变量是我的东西从来没有完全理解 - 希望这里的某个人能指引我走向正确的方向。 :)

$data['query']->section[${$child['id']}]->subsection[${$grandchild['id']}]->page[${$greatgrandchild['id']}] = "Fluffy Rabbit"; 

Onviously以上不工作,但如果我硬编码一个变量,例如:

$data['query']->section[0]->subsection[3]->page[6] = "Very Fluffy Rabbit"; 

...那么一切都很好,所以很明显我不能建立我的动态变量正确。有任何想法吗?

UPDATE:

嗯,确定我应该指出,这些不是在阵列中的键 - 我使用被指定为每个节点的属性的ID寻址在XML节点,所以XML具有以下结构:

<subtitles> 
<section id="0"> 
<subsection id="0"> 
<page id="1">My content that I want to write</page> 
<page id="2">My content that I want to write</page> 
<page id="3">My content that I want to write</page> 
</subsection> 
</section> 
</subtitles> 

希望这有助于更好地解释事情。 :)

+4

变量变量是邪恶的,应该避免。特别是在你的情况下,即使你在写作时也无法弄清楚......想象一下,在需要修复一个bug时,弄清楚一年发生了什么是多么困难。编写可读代码。写简单的代码... – ircmaxell 2010-11-02 13:12:51

+1

@ircmaxell它可以简化代码,甚至使其更具可读性。例如,想象一个工厂,巨大的开关(创建几十个类),而不是这段代码:'factory($ class_name){return new $ class_name()}' – 2010-11-02 13:22:06

+0

@Itay Moav:在这种情况下,您的应用程序将如果添加一个不存在的$ class_name,就会死亡。 – 2010-11-02 13:28:02

回答

6

为什么你认为你需要动态变量?不这只是做你想做的:

$data['query']->section[$child['id']]->subsection[$grandchild['id']]->page[$greatgrandchild['id']] = "Fluffy Rabbit"; 
1
$foo = "hello"; 

$$foo = " world"; 

//echo $foo.$$foo; 

echo $foo.$hello; 
+0

这是更正确的解释:'$ foo =“hello”; $$ foo =“world”; echo $ foo。$ hello;' – pltvs 2010-11-02 13:17:00

+0

@ Alexander.Plutov良好的通话,我更新了我的答案。 – 2010-11-02 13:22:12

+0

输出'你好'。因为$ foo有一个空格。) – pltvs 2010-11-02 13:23:15

1

在这个例子中,你不需要动态变量。

如果$孩子[ “ID”]的值为0,$孙子[ “ID”]有值3和$ greatgrandchild [ “ID”]将值6,你应该使用类似:

$data['query']->section[$child['id']]->subsection[$grandchild['id']]->page[$greatgrandchild['id']] = "Fluffy Rabbit"; 

通常使用动态变量是这样的:

$variable = "variableName"; 

$$variable = "Some value"; 

echo $variableName; 

这将显示:

Some value 

编辑

完全符合ircmaxell

1

我看起来像你用好老array键混淆variable variables同意。变量变量是一种机制,允许读取(或写)的值到一个变量名字是未知的或能改变的,老实说,他们几乎没有必要:

<?php 

$first_name = 'John'; 
$last_name = 'Smith'; 

$display = 'first_name'; 
echo $$display; // Prints 'John'; 

$display = 'last_name'; 
echo $$display; // Prints 'Smith'; 

然而,你的代码建议你只希望访问数组内的关键:

<?php 

$person = array(
    'first_name' => 'John', 
    'last_name' => 'Smith', 
); 

$display = 'first_name'; 
echo $person[$display]; // Prints 'John'; 

$display = 'last_name'; 
echo $person[$display]; // Prints 'Smith'; 

在PHP中,数组键是一个整数或字符串,但它并不需要是文字:你可以从一个变量的关键。

0
$foo='bobo'; 
echo $foo;//"bobo" 
$$foo='koko'; 
echo $$foo;//"koko" 
echo $bobo;//"koko"