在PHP eval()中调用用户定义的函数 [英] Calling user defined functions in PHP eval()

查看:151
本文介绍了在PHP eval()中调用用户定义的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在进行使用eval()函数的php测试,但似乎eval()无法正确调用用户定义的函数.

I was been doing a php testing which uses eval() function, but it seems that eval() can't call user defined functions properly.

请参见我的示例:

function equals($a,$b){  
        if ($t == $r){  
        return true;  
        }  
    else{  
                throw new Exception("expected:<".$r."> but was:<".$t.">");  
    }  
}
eval("$test = 1;");  
try{  
    echo eval("equals($test,1);");  
}  
catch (Exception $e) {  
    echo $e->getMessage();  
}  

但是我收到的总是像"expected:< 1> but was:<>",但是如果我已经做了

but what I have received is always like "expected:<1> but was:<>", but if I have do an

echo $test;

我可以拿1.

我曾尝试按照PHP eval()手册将$更改为\ $,但似乎破坏了eval函数. ( http://php.net/manual/en/function.eval.php)

I have tried changing $ to \$ by following the PHP eval() Manual, but it seems to break the eval function. (http://php.net/manual/en/function.eval.php)

所以我现在有点累了,有人可以帮我解决这个问题.非常感谢.

So I am a bit of stack now, can someone help me with the problem. Thank you very much.

推荐答案

您缺少return

echo eval("return equals(\"$test\",1);");

摘自PHP手册

eval()返回NULL,除非return为 在评估的代码中调用,其中 传递给return的值是 回来.如果存在解析错误 评估的代码,eval()返回 虚假并执行以下内容 代码正常继续.

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.

eval()

避免按照@Delan的建议使用eval().

avoid to use eval() as @Delan suggested.

这篇关于在PHP eval()中调用用户定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆