Using PHP eval to run code causes Fatal error: Cannot redeclare function

Using PHP eval to run code causes Fatal error: Cannot redeclare function

我有一个 PHP 脚本,它从数据库中选择许多 PHP 代码片段之一并使用 eval 执行它。在某些情况下,如果两个代码片段试图声明一个具有相同名称的函数,我会得到致命错误 "cannot redeclare function"。编辑代码片段中的函数名称不是一种选择。有什么方法可以创建作用域或者让函数相互覆盖吗?或者其他更好的想法?

谢谢。

编辑:循环此代码。

ob_start();
try {
    $result = eval($source_code);
} catch(Exception $e) {
    echo "error";
}
$error = ob_get_clean();

你有三个选择,真的。

function_exists()

// this will check for the function's existence before trying to declare it
if(!function_exists('cool_func')){
    function cool_func(){
        echo 'hi';
    }
}

// business as usual
cool_func();

将函数分配给变量

// this will automatically overwrite any uses of $cool_func within the current scope
$cool_func = function(){
    echo 'hi';
}

// call it like this
$cool_func();

Namespacing 在 PHP >= 5.3.0

/* WARNING: this does not work */
/* eval() operates in the global space */
namespace first {
    eval($source_code);
    cool_func();
}

namespace second {
    eval($source_code);
    cool_func();
}

// like this too
first\cool_func();
second\cool_func();

/* this does work */
namespace first {
    function cool_func(){echo 'hi';}
    cool_func();
}

namespace second {
    function cool_func(){echo 'bye';}
    cool_func();
}

对于第二个示例,您需要在每个需要使用的范围内 eval() 一次数据库代码 $cool_func,见下文:

eval($source_code);

class some_class{
    public function __construct(){
        $cool_func(); // <- produces error
    }
}

$some_class = new some_class(); // error shown

class another_class{
    public function __construct(){
        eval($source_code); // somehow get DB source code in here :)
        $cool_func(); // works
    }
}

$another_class = new another_class(); // good to go

好吧,正如其他人所说,您应该 post 代码以便我们更好地帮助您。但是您可能想要查看 PHP OOP,因为您可以为 类 中的方法赋予范围并这样引用它们:

ClassOne::myFunction();
ClassTwo::myFunction();

查看更多:http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php