2017-07-30 34 views
0

我正在学习在php中使用名称空间,并且我正在尝试在调用常量时在名称空间名称中放入一个变量。 这是我的代码。调用一个变量的名称空间

fruits2.php

<?php 
namespace fruits\red; 
const redfruit = 'tomato'; 

fruits1.php

<?php 
namespace fruits; 

require_once('fruits2.php'); 

const myconst = 'banana'; 

echo myconst; // displays banana 

echo '<br>'; 

echo \fruits\red\redfruit; // displays tomato 

echo '<br>'; 
$color = 'red'; 
echo \fruits\$color\redfruit; // Parse error: syntax error, unexpected '$color' (T_VARIABLE), expecting identifier (T_STRING) 

我不明白我怎么能叫恒在这最后一道防线。我尝试了以下,但它被认为是一个简单的字符串。

echo '\fruits\\'.$color.'\\redfruit'; 

我敢肯定,我应该能够做到这一点,因为在调用这个代码的另一部分的类时,我可以做一些非常相似:

$name = '\fruits\basket\\'.$color.'\\eat'; 
$c = new $name(); //this works 

任何人知道答案到那个?谢谢!

+0

你不能因为你不允许把变量放在任何你想要的地方,比如'class foo extends $ var {..}'这样也不行。与'公共函数$ var($ a,$ b)''一样,你只是不应该这样做,即使PHP需要有规则,Man! – ArtisticPhoenix

回答

0

使用constant关键字:

$name = constant("fruits\\$color\\redfruit"); 

你必须逃脱斜线。 此外,该名称必须是完全限定的(相对于根名称空间)。

+0

constant()函数做到了这一点。谢谢您的帮助:) – Yann

相关问题