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 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果