如何在对 eval() 的嵌套调用中使用单引号?

How can I use single quotes with nested calls to eval()?

我正在尝试在对 eval():

的嵌套调用中使用单引号
eval('eval(\'echo 'hi\';\');');

但是,这会触发以下错误:

syntax error, unexpected 'hi' (T_STRING)

如何使用单引号并解决此错误?

您在转义单引号时遇到问题。您可以使用双引号代替——"hi" 而不是 'hi'

eval('eval(\'echo "hi";\');');

如果您需要使用单引号,则转义单引号的反斜杠本身也需要转义,并带有一对额外的反斜杠 (\);即:

eval('eval(\'echo \\'hi\\';\');');

这产生:

hi

正如您所想象的,随着嵌套级别的增加,这会很快变得混乱。

值得注意的是 eval() 被认为是危险的,你应该只在非常慎重的情况下使用它,你已经彻底评估过使用它没有风险,并且没有更好的方法来实现你想做的事。

PHP documentation 中所述:

Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

值得在 Stack Overflow 上搜索一些 discussion on its usage

希望这对您有所帮助:)