dsvs50005 2016-04-29 15:42
浏览 407
已采纳

使用PHP eval运行代码导致致命错误:无法重新声明函数

I have a PHP script that selects one of many PHP code snippets from the database and executes it using eval. In some cases if two code snippets try to declare a function with the same name, I get the fatal error "cannot redeclare function". Editing the function names in the code snippets is not an option. Is there some way to create a scope or maybe have the functions overwrite each other? Or any other better ideas?

Thanks.

Edit: Loops this code.

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

2条回答 默认 最新

  • douhuike3199 2016-04-29 15:52
    关注

    You have three choices, really.

    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();
    

    Assign function to a variable

    // 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 in 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();
    }
    

    With the second example you would need to eval() the DB code once within every scope which you need to use $cool_func, see below:

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题