PHP 嵌套函数的用途是什么?

2022-08-30 08:04:42

在JavaScript中,嵌套函数非常有用:闭包,私有方法以及您拥有的东西。

嵌套 PHP 函数的用途是什么?有没有人使用它们,目的是什么?

这是我做的一个小调查

<?php
function outer( $msg ) {
    function inner( $msg ) {
        echo 'inner: '.$msg.' ';
    }
    echo 'outer: '.$msg.' ';
    inner( $msg );
}

inner( 'test1' );  // Fatal error:  Call to undefined function inner()
outer( 'test2' );  // outer: test2 inner: test2
inner( 'test3' );  // inner: test3
outer( 'test4' );  // Fatal error:  Cannot redeclare inner()

答案 1

如果您使用的是 PHP 5.3,则可以通过匿名函数获得更多类似 JavaScript 的行为:

<?php
function outer() {
    $inner=function() {
        echo "test\n";
    };

    $inner();
}

outer();
outer();

inner(); //PHP Fatal error:  Call to undefined function inner()
$inner(); //PHP Fatal error:  Function name must be a string
?>

输出:

test
test

答案 2

基本上没有。我一直认为这是解析器的副作用。

Eran Galperin错误地认为这些功能在某种程度上是私有的。在运行之前,它们只是未声明。它们也不是私人范围的;它们确实污染了全球范围,尽管被推迟了。作为回调,外部回调仍然只能调用一次。我仍然不明白在数组上应用它有什么帮助,数组很可能多次调用别名。outer()

我能挖掘到的唯一“现实世界”的例子是这个,它只能运行一次,并且可以重写得更干净,IMO。

我能想到的唯一用途是模块调用一个方法,该方法在全局空间中设置了几个嵌套方法,并结合了[name]_include

if (!function_exists ('somefunc')) {
  function somefunc() { }
}

检查。

PHP的OOP显然是一个更好的选择:)


推荐