【问题标题】:Eval Interface with const attributes带有 const 属性的 Eval 接口
【发布时间】:2014-06-26 17:11:03
【问题描述】:

这是我的代码:

$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);

它工作,返回 1,但在运行时:

var_dump(Foo::NAME);

或:

var_dump(Foo::CURRENT_JOB);

它不起作用,这是错误:

使用未定义的常量 toan - 假设...

怎么了?有人可以帮助我吗?

【问题讨论】:

  • 怎么了? 你在滥用语言。您能否描述一下您想要完成的工作,也许我们可以帮助您找到更好的解决方案。
  • 我想为 Foo 类创建动态 const 属性:D

标签: php eval


【解决方案1】:

这是因为您将$value 连接为常量。

$interface .= 'const '.strtoupper($key).' = '.$value.';';

以上翻译为:

const NAME = Paul;

你需要用双引号括起来"'.$value.'"

$interface .= 'const '.strtoupper($key).' = "'.$value.'";';

翻译为:

const NAME = "Paul";

【讨论】:

  • $value 可能是用户输入,因此使用eval() 以这种方式创建动态类可能是一个非常糟糕的主意,特别是因为 OP 似乎缺乏对诸如知道之类的事情的基本了解常量和字符串的区别。
猜你喜欢
  • 1970-01-01
  • 2015-12-20
  • 2011-01-02
  • 2022-10-23
  • 2012-12-14
  • 1970-01-01
  • 2023-01-01
  • 2017-07-16
  • 1970-01-01
相关资源
最近更新 更多