我正在学习在 php 中使用命名空间,并且我试图在调用常量时在命名空间名称中放置一个变量。这是我的代码。
水果2.php
<?php
namespace fruits\red;
const redfruit = 'tomato';
水果1.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
有人知道答案吗?谢谢!
使用constant
关键字:
$name = constant("fruits\\$color\\redfruit");
你必须逃避斜线。此外,名称必须是完全限定的(相对于根命名空间)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句