dongyiba8082 2014-12-03 00:11
浏览 43
已采纳

如何在使用字符串连接自动创建PHP代码后执行它?

I have a function that will create a php code that will do a bitwire operation.

this code is generated by function

1 | 2 | 4

what I want to do is return the result of the operation. return (1 | 2 | 4); I tried to use eval() but I get the following error

 Parse error: syntax error, unexpected end of file in ..... : eval()'d code on line 1

The flowing is my code

<?php

class Roles
{

    protected $rolesList = array();

    public function __construct(){

        $this->rolesList = array(
                                'can_use' => 1,
                                'can_view' => 2,      //0000000001
                                'can_update' => 4,    //0000000010
                                'can_insert' => 8,    //0000000100
                                'can_delete' => 16     //0000001000
                            );

    }

    public function mapRoles(){

        if ( func_num_args() == 0 ){
            return false; //no args passed
        }

        $tmp = array();
        $parmeters = func_get_args();

        foreach($parmeters as $arg){
            $tmp[] = $this->rolesList[$arg];
        }

        $cmd = implode(' | ', $tmp);
        return eval($cmd);
    }
}

?>
  • 写回答

1条回答 默认 最新

  • duanguilin2007 2014-12-03 00:19
    关注

    function that will create a php code that will do a bitwire operation

    Usually one does not generate php code in their code.

    Instead you might just iterate over array elements and mutually | it:

    $val = 0;
    foreach($parmeters as $arg) {
        $val |= $this->rolesList[$arg];
    }
    

    the other one line implementation that uses an array_reduce might look like this:

    $val = array_reduce($data, function($a, $b) { return $a | $b; }, 0);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗