douyuben9434 2019-04-06 18:33
浏览 316

PHP Eval替代生成动态if条件

I have the following php code where I'm trying to generate a dynamic if condition using eval:

$categoryId = $_REQUEST['category_id'];
$locationId = $_REQUEST['location_id'];

$recordId = 1;

$criteria = [(!empty($categoryId) ? '(isInCategory($recordId, $categoryId))' : ''),
             (!empty($locationId) ? '(isInLocation($recordId, $locationId))' : '')];

$check = implode(' && ', array_filter($criteria));

// $check will be  
// (isInCategory($recordId, $categoryId)) && (isInLocation($recordId, $locationId))
// if $categoryId and $locationId are not empty

if(eval("return $check;")) 
{ 
    echo 'true'; 
}
else
{
   echo 'false';
}

The problem is the entire code itself is within an eval statement so basically I'm ending up with an eval inside an eval which is throwing an error - can't really troubleshoot the error because all I get is a friendly error page so I'm assuming that is the case i.e. you cant use eval inside another eval???

I'm forced to use a propriety product so this is my limitation. Is there a way I can refactor the eval in the above if statement via some other technique.

I read some stuff about using call_user_func() but I'm new to this. Any help would be appreciated.

  • 写回答

0条回答

    报告相同问题?

    悬赏问题

    • ¥15 树莓派与pix飞控通信
    • ¥15 自动转发微信群信息到另外一个微信群
    • ¥15 outlook无法配置成功
    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题