2016-04-29 71 views
-4

我有一个PHP脚本,从数据库中选择许多PHP代码片段之一,并使用eval执行它。在某些情况下,如果两个代码片段尝试声明具有相同名称的函数,则会发生致命错误“无法重新声明函数”。编辑代码片段中的函数名称不是一个选项。有什么方法可以创建一个范围或者可能有功能相互覆盖?还是其他更好的想法?使用PHP eval来运行代码导致致命错误:无法重新声明函数

谢谢。

编辑:循环此代码。

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

我们可以看到你实际上是试图做? – DevDonkey

+2

@DevDonkey我可以看到完美的代码!你不是通灵吗?获取它:-) – MonkeyZeus

+0

如果您发布了一些代码,我们可能会提供帮助,否则重命名一个函数或将其移动到一个类中可能会失败。你也可以使用'function_exists' – DaOgre

回答

1

你有三种选择,真的。

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

在PHP Namespacing> = 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范围内的DB一次代码,见下图:

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 
+0

有1000个代码片段。没有办法编辑每一个。同样,即使函数具有相同的名称并不意味着它们做同样的事情,所以我不能使用!function_exists – user4712608

+0

@ user4712608请参阅我的编辑:-) – MonkeyZeus

+0

但是,并非所有这些解决方案都需要编辑代码数据库中的片段? – user4712608

0

嗯,正如其他人所说,你应该张贴代码,以便我们能更好地帮助你。但是你可能想看看PHP OOP,你可以在类内发挥好方法,并引用它们的方式:

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

的看到这个更多:http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php

+0

有1000个代码片段。我无法编辑每一个。这将需要几个月。 – user4712608

+0

然后我猜你已经搞砸了,因为你不能声明两个具有相同名称的函数在PHP中的相同范围内运行。如果你不想编辑任何代码,你到底希望如何解决这个问题? – Monty

相关问题