2011-06-20 52 views
0

我有以下代碼:PHP匿名函數會導致對一些設施語法錯誤

$file_check_method_func = function($n) { 
     $n = absint($n); 
     if(1 !== $n) { $n = 0; } 
     return $n; 
    }; 
    $valid['file_check_method'] = array_map($file_check_method_func, $input['file_check_method']); 

這個工作對我的PHP 5.3.5安裝,但是當我在PHP 5.2.15安裝運行這段代碼,我得到:

Parse error: syntax error, unexpected T_FUNCTION in /home/xxxx/public_html/xxxx/xxxxxxx/wp-content/plugins/wordpress-file-monitor-plus/classes/wpfmp.settings.class.php on line 220 

220行是上述代碼的第一行。

所以我的問題是,是否有錯誤地寫在我的代碼會給這個錯誤?如果不是因爲PHP 5.2.15中的錯誤或不支持的功能?如果是,那麼我怎麼寫上面的代碼,以避免產生錯誤?

上面的代碼是在一個類中的函數。

回答

7

匿名函數是在5.3

增加對於早期版本的功能,創建一個名爲功能,按名稱引用它。例如:

function file_check_method_func($n) { 
    $n = absint($n); 
    if(1 !== $n) { $n = 0; } 
    return $n; 
} 
$valid['file_check_method'] = array_map('file_check_method_func', $input['file_check_method']); 

或類中:

class Foo { 
    protected function file_check_method_func($n) { 
    $n = absint($n); 
    if(1 !== $n) { $n = 0; } 
    return $n; 
    } 
    function validate($input) { 
    $valid = array(); 
    $valid['file_check_method'] = array_map(array($this, 'file_check_method_func'), $input['file_check_method']); 
    return $valid; 
    } 
} 

我會強烈建議依靠create_function

+0

你只有一半提供一個答案...... – Brady

+0

錯了,5.2知道匿名函數 – Raffael

+0

@Raffael他們是不是真的匿名 - 這個名字只是在運行時創建的,但在技術上'create_function '只是'eval' +隨機名稱生成器的一個包裝。 – troelskn

3

該示例中的匿名函數的語法只能在PHP> = 5.3中使用。在PHP 5.3之前,只能使用create_function()創建匿名函數。

+0

您只提供了一半的答案... – Brady

+0

錯誤,5.2知道匿名函數 – Raffael

+0

沒錯。更新了答案。我總是發現'create_function()'難以置信的醜陋,我很少使用它,現在我甚至都沒有想過它。 – rid