What are PHP nested functions for?

2019-01-04 00:43发布

In JavaScript nested functions are very useful: closures, private methods and what have you..

What are nested PHP functions for? Does anyone use them and what for?

Here's a small investigation I did

<?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()

11条回答
Ridiculous、
2楼-- · 2019-01-04 01:19

I know this is an old post but fwiw I use nested functions to give a neat and tidy approach to a recursive call when I only need the functionality locally - e.g. for building hierarchical objects etc (obviously you need to be careful the parent function is only called once):

function main() {
    // Some code

    function addChildren ($parentVar) {
        // Do something
        if ($needsGrandChildren) addChildren ($childVar);
    }
    addChildren ($mainVar); // This call must be below nested func

    // Some more code
}

A point of note in php compared with JS for instance is that the call to the nested function needs to be made after, i.e. below, the function declaration (compared with JS where the function call can be anywhere within the parent function

查看更多
聊天终结者
3楼-- · 2019-01-04 01:21

There is none basically, I've always treated this as a side effect of the parser.

Eran Galperin is mistaken that these functions are somehow private, they are simply undeclared until outer() is run. They are also not privately scoped, they do polute the global scope albeit delayed. And as a callback the outer callback could still only be called once. I still don't see how that's helpful applying it on an array which very likely calls the alias more than once.

The only 'real world' example I could dig up is this which can only run once and could be rewritten cleaner IMO.

The only use I can think of is for modules to call a [name]_include method which sets several nested methods in the global space combined with

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

checks.

PHP's OOP would obviously be a better choice :)

查看更多
劫难
4楼-- · 2019-01-04 01:24

If you are using PHP 5.3 you can get more Javacript-like behaviour with an anonymous function:

<?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
?>

Output:

test
test
查看更多
倾城 Initia
5楼-- · 2019-01-04 01:25

Nested functions are useful if you want the nested function to utilize a variable that was declared within the parent function.

<?php
ParentFunc();
function ParentFunc()
{
  $var = 5;
  function NestedFunc()
  {
    global $var;
    $var = $var + 5;
    return $var;
  };
  echo NestedFunc()."<br>";
  echo NestedFunc()."<br>";
  echo NestedFunc()."<br>";
}
?>
查看更多
相关推荐>>
6楼-- · 2019-01-04 01:29

In webservice calling we found it a much lower overhead (memory and speed) dynamically including in a nested fashion, individual functions over libraries full of 1000s of functions. The typical call stack might be between 5-10 calls deep only requiring linking a dozen 1-2kb files dynamically was better than including megabytes. This was done just by creating a small util function wrapping requires. The included functions become nested within the functions above the call stack. Consider it in contrast to classes full of 100s of functions that weren't required upon every webservice call but could also have used the inbuilt lazy loading features of php.

查看更多
我欲成王,谁敢阻挡
7楼-- · 2019-01-04 01:30

All of my php is OO, but I do see a use for nested functions, particularly when your function is recursive and not necessarily an object. That is to say, it does not get called outside of the function it is nested in, but is recursive and subsequently needs to be a function.

There's little point in making a new method for the express use of a single other method. To me that's clumsy code and sort-of not the point of OO. If you're never going to call that function anywhere else, nest it.

查看更多
登录 后发表回答