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


How to execute PHP code after automaticly creating it using string concatenation?

我有一个函数,它将创建一个php代码,该代码将执行bitwire操作。

此代码由函数生成

1 | 2 | 4

我想做的是返回操作的结果。 return (1 | 2 | 4);我尝试使用eval()但出现以下错误

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

流动是我的代码

<?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);
    }
}
?>

将创建将执行位线操作的 PHP 代码的函数

通常不会在他们的代码中生成 php 代码。

相反,您可能只是遍历数组元素并相互|它:

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

使用array_reduce的另一行实现可能如下所示:

$val = array_reduce($data, function($a, $b) { return $a | $b; }, 0);