2011-10-15 63 views
0

我有這個要求,指出我必須有一個函數簽名作爲數據庫列中的值。所以我需要做的是獲取那個值,然後調用代碼中的函數。例如....假設我在一個名爲「Signature」的數據庫中有一個列,其值爲SendMail();.我需要能夠獲得返回值,然後將其存儲在另一個表中。問題是當我在$ i ['Signature']函數被調用時使用eval函數時,但我無法獲得返回值。我究竟做錯了什麼?這裏有一個例子:從PHP中的數據庫調用函數

$query = "SELECT signature FROM tbl WHERE id = 1 "; 
$signature = mysql_query($query); 
while ($i = mysql_fetch_array($signature)){ 
    //Here the function is being called properly but I can't get the return value. 
    $email= eval($i['Signature']); 
    if(mysql_num_rows($i) == 0){ 
     //insert the returned value into another table. 
     $insertString = "INSERT INTO tbl (email) VALUES ('$email')"; 
    } 
} 

function SendMail() 
{ 
    $email= 'Have a great day' 
    return $email; 
} 

當然我也會勢必會得到一些「EVAL被邪惡」的意見,因此,如果有一個更好的辦法,請告知。

+1

如果必須堅持使用eval,至少應檢查簽名列的內容是否實際上首先是有效的。也許通過'function_exists'函數:http://php.net/manual/en/function.function-exists.php – imm

回答

3

docs

eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. 

因此,你應該添加return

$email= eval('return ' . $i['Signature']); 

或者:

eval('$email = ' . $i['Signature']); 
+0

我會給你一個鏡頭。我剛剛讀過這個聲明,但並沒有完全理解它。 – Robert

+0

像一個魅力工作。謝謝。 – Robert

1

你會過得更好存儲函數的名稱作爲一個字符串在一列中,並將參數傳遞給函數as在另一列中的字符串數組。然後,您可以使用call_user_func從函數中獲取返回值而不使用eval()

+0

有趣。我會給這個鏡頭。 – Robert