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 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决