Php 具有常量属性的Eval接口
这是我的代码:Php 具有常量属性的Eval接口,php,eval,Php,Eval,这是我的代码: $array = array( 'id' => 1, 'name' => 'Paul', 'current_job' => 'coder' ); $interface = 'interface PropertyInterface {'; foreach ($array as $key => $value) { $interface .= 'const '.strtoupper($key).' = '.$value.';';
$array = array(
'id' => 1,
'name' => 'Paul',
'current_job' => 'coder'
);
$interface = 'interface PropertyInterface {';
foreach ($array as $key => $value) {
$interface .= 'const '.strtoupper($key).' = '.$value.';';
}
$interface .= '}';
eval($interface);
class Foo implements PropertyInterface
{
}
运行时:
var_dump(Foo::ID);
var_dump(Foo::NAME);
它正在工作,返回1,但运行时:
var_dump(Foo::ID);
var_dump(Foo::NAME);
或:
它不工作,这是错误:
使用未定义的常数toan-假定
怎么了?有人能帮我吗?这是因为您将
$value
串联为常量
$interface .= 'const '.strtoupper($key).' = '.$value.';';
以上翻译为:
const NAME = Paul;
const NAME = "Paul";
您需要用双引号括起来。$value。“
也就是说:
const NAME = Paul;
const NAME = "Paul";
怎么了?你在滥用语言。你能描述一下你想完成什么,也许我们可以帮助你找到更好的解决方案。我想为类Foo创建动态常量属性:DPossible duplicate
$value
可能是用户输入,所以使用eval()
以这种方式创建动态类可能是一个非常糟糕的主意,尤其是因为OP似乎对一些事情缺乏基本的理解,比如知道常量和字符串之间的区别。