2012-08-14 120 views
2

可能重複:
What are PHP nested functions for?PHP中嵌套函數聲明的用例是什麼?

PHP允許像嵌套函數聲明這樣:

function foo() { 
    function bar() { 
     return "bar"; 
    } 
    return "foo"; 
} 

但什麼是用例這樣的語法?內部bar被放到全局命名空間 所以它不是垃圾收集,可以從外部使用 外部功能,並提供了很多混淆和可能的錯誤。對於 示例調用foo兩次會導致錯誤,除非在if(!is_callable('bar'))中包裝 聲明。

因爲創建的混淆,使用嵌套聲明創建條件聲明並不好 。 「爲什麼它會抱怨 沒有這樣的功能,當它在那裏工作得很好時?!?!」。

回答

6

好,有條件的函數的聲明可能是唯一合法使用的情況下,有隻爲了向後兼容提供回退:

function makeSureAllDependenciesExist() { 
    if (!function_exists('someFunctionThatOnlyExistsInNewerPhpVersions')) { 
     function someFunctionThatOnlyExistsInNewerPhpVersions() { 
      // fallback implementation here 
     } 
    } 
} 

其他,有確實沒有理由使用嵌套函數聲明。