PHP eval(array_as_string) returns null

女生的网名这么多〃 提交于 2019-12-30 11:18:12

问题


$arr = eval("array('foo'=>'bar');");

// returns null
var_dump($arr);

Can someone please explain why did I get null instead of an array?


回答1:


You need to return the array.

From the docs:

eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned.

So you need to do:

$arr = eval("return array('foo'=>'bar');");



回答2:


Did you mean

eval("\$arr = array('foo'=>'bar');"); 

var_dump($arr);



回答3:


The eval function executes the php code given to it. As your code returns nothing, it gives null. You need to return the array and store it in a variable like,

$arr = eval("return array('foo'=>'bar');");



回答4:


First of all, eval is highly discouraged as explained in the manual.

Also, you should be doing something like $arr = eval("return array('foo'=>'bar');"); ie. initialising $arr with the eval function. See it in action here



来源:https://stackoverflow.com/questions/12976254/php-evalarray-as-string-returns-null

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