Can php eval return a boolean value?

本小妞迷上赌 提交于 2019-12-24 09:49:25

问题


I cant seem to get eval to return a boolean value for '(4 > 5)'

Is this possible? If not how might I get this to work (without writing a parser)

I have tried this:

$v = eval('return (10 > 5)');
var_dump($v);

// Result = bool(false)

UPDATE

Thanks to @Pekka - I added a semicolon to the above code and it works.


回答1:


See the manual:

eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. If there is a parse error in the evaluated code, eval() returns FALSE and execution of the following code continues normally. It is not possible to catch a parse error in eval() using set_error_handler().

It'll work like @mhitza already said in the comment. I would just add brackets to be safe:

    $x = eval('return (4 < 5);');
    echo $x;



回答2:


Please enable display_errors & a suitable error_reporting before turning to the community:

Parse error: syntax error, unexpected $end in -(2) : eval()'d code on line 1

Aha:

eval('return (10 > 5);');

Notice the ;.




回答3:


This has probably already been answered sufficiently...but what helps me is to always think of the eval in PHP as the entire line of code, and don't forget the semi-colon, e.g.

eval('\$myBooleanValue = 4 > 5;');
return $myBooleanValue;

Don't try stuff like this:

$myBooleanValue = eval('4 > 5');


来源:https://stackoverflow.com/questions/4028043/can-php-eval-return-a-boolean-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!