【问题标题】:What is the use cases for nested function declarations in PHP? [duplicate]PHP中嵌套函数声明的用例是什么? [复制]
【发布时间】:2012-08-10 13:22:25
【问题描述】:

可能重复:
What are PHP nested functions for?

PHP 允许这样的嵌套函数声明:

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

但是这种语法的用例是什么?内部bar 放到 全局命名空间,因此不会被垃圾收集,可从外部使用 外部函数并提供了很多混乱和可能的错误。为了 示例调用 foo 两次会导致错误,除非您将 if(!is_callable('bar')) 中的声明。

使用嵌套声明创建条件声明不好 要么,因为它造成的混乱。 “它为什么抱怨 没有这样的功能,当它在那里工作得很好时?!?!“。

【问题讨论】:

    标签: php


    【解决方案1】:

    嗯,条件函数声明可能是唯一合法的用例,并且只是为了向后兼容提供后备:

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

    除此之外,确实没有什么理由使用嵌套函数声明。

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 2016-01-03
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 2011-11-09
      • 2010-09-29
      相关资源
      最近更新 更多