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()
A nested function can access other local functions, variables, constants, types, classes, etc. that are in the same scope, or in any enclosing scope, without explicit parameter passing, which greatly simplifies passing data into and out of the nested function. This is typically allowed for both reading and writing.
A function is a piece of code that takes another input in the form of a parameter, processes it, and then returns a value. A PHP Function feature is a piece of code that can be used over and over again and accepts argument lists as input, and returns a value. PHP comes with thousands of built-in features.
no, there's nothing wrong with that at all, and in js, it's usually a good thing. the inside functions may not be a pure function, if they rely on closure variables. If you don't need a closure or don't need to worry about polluting your namespace, write it as a sibling.
The nested function's name is local to the block where it is defined. For example, here we define a nested function named square, and call it twice: foo (double a, double b) { double square (double z) { return z * z; } return square (a) + square (b); }
If you are using PHP 5.3 you can get more JavaScript-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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With