What are PHP nested functions for?

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

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

Here is a little research 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() 
+65
php nested-function
Jan 06 '09 at 9:56
source share
9 answers

Basically, no, I always saw this as a side effect of the parser.

Eran Halperin mistakenly believes that these functions are somehow private, they simply were not declared until outer() run. They are also not privately covered; they do dispute global coverage, although they are delayed. And as a callback, an external callback can still only be called once. I still don’t see how useful it is to apply to an array that most likely calls an alias more than once.

The only example of a “real world” I could dig is this , which can only be run once and can be rewritten with a cleaner IMO.

The only thing I can think of is to use modules to call the [name] _include method, which sets up several nested methods in global space in combination with

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

checks.

PHP OOP will obviously be the best choice :)

+74
Jan 6 '09 at 10:19
source share

If you use PHP 5.3, you can get more behavior like Javacript 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 
+66
May 20 '11 at 10:12
source share

[Rewritten in accordance with the comment by @PierredeLESPINAY.]

This is not just a side effect, but a really very useful feature for dynamically changing the logic of your program. This is from PHP procedural days, but it can also be useful in OO architectures if you want to most easily implement alternative implementations for certain stand-alone functions. (While OO is the best choice in most cases, it is an option, not a mandate, and some simple tasks do not need additional collapse.)

For example, if you dynamically / conditionally load plugins from your framework and want the life of the plugin authors to be very simple, you can provide standard implementations for some critical functions that the plugin has not redefined:

 <?php // Some framework module function provide_defaults() { // Make sure a critical function exists: if (!function_exists("tedious_plugin_callback")) { function tedious_plugin_callback() { // Complex code no plugin author ever bothers to customize... ;) } } } 
+9
Dec 15 '13 at 12:57
source share

Functions defined in functions that I don’t see much, but conditionally defined functions that I can. For example:

 if ($language == 'en') { function cmp($a, $b) { /* sort by English word order */ } } else if ($language == 'de') { function cmp($a, $b) { /* sort by German word order; yes it different */ } } // etc 

And then all you have to do is use the cmp function in things like usort () calls so that you don't interfere with language checks throughout your code. Now I have not done this, but I can see the arguments for this.

+6
Jan 06 '09 at 12:11
source share

All my php are OO, but I see use for nested functions, especially when your function is recursive and not necessarily an object. That is, it is not called outside the function in which it is nested, but is recursive and subsequently must be a function.

There is little point in creating a new method for express use of one other method. To me, this awkward code and sort is not an OO point. If you never call this function anywhere, insert it.

+2
Apr 30 2018-12-12T00:
source share

In the webservice call, we found it to be much lower overhead (memory and speed) dynamically, including in a nested way, by separate library functions, full of 1000 functions. A typical call stack can range from 5 to 10 calls, but just to link a dozen files of 1-2 kbytes dynamically was better than including megabytes. This was done simply by creating a small utility that requires wrapping. Included functions become nested in functions above the call stack. Think of this, unlike classes, full of 100 functions that were not required every time webservice was called, but could also use the lazy php built-in load functions.

+1
Jan 09 '14 at 6:27
source share

All of the above, you can simply create a nested function to replace some localized repeating code inside the function (which will be used only inside the parent function). Some may say that they simply create private methods (or smaller blocks of code), but it hides the water when the super-special task (which is exclusive to the parent) needs to be modular, but the rest of the class (or the global space in the procedural program) is not necessarily accessible . The good news is that if it turns out that you need this function somewhere else, the fix is ​​pretty basic (move the definition to a more central place).

Generally speaking, using JavaScript as the standard for evaluating other C programming languages ​​is a bad idea. JavaScript is certainly its own animal compared to PHP, Python, Perl, C, C ++ and Java. Of course, there are many common similarities, but the detailed detailed details (JavaScript link: The Definitive Guide, 6th Edition, chapters 1-12), when you pay attention to this, make the core JavaScript unique, beautiful, different, simple and complex all at the same time. These are my two cents.

Just to be clear, I'm not saying that nested functions are private. Just this attachment can help to avoid clutter when you need something trivial to be modular (and only a parent function is required).

+1
Sep 27 '15 at 1:39 on
source share

Nested functions are useful in Memoization (caching results for better performance).

 <?php function foo($arg1, $arg2) { $cacheKey = "foo($arg1, $arg2)"; if (! getCachedValue($cacheKey)) { function _foo($arg1, $arg2) { // whatever return $result; } $result = _foo($arg1, $arg2); setCachedValue($cacheKey, $result); } return getCachedValue($cacheKey); } ?> 
0
May 24 '11 at 16:56
source share

Nested functions are useful if you want the nested function to use a variable that was declared in 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>"; } ?> 
0
Nov 14 '15 at 0:39
source share