Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are PHP nested functions for?

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() 
like image 750
meouw Avatar asked Jan 06 '09 09:01

meouw


People also ask

What is the point of nested functions?

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.

What is the purpose of functions in PHP?

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.

Is it good practice to use nested functions?

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.

What is nesting of functions give an example?

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); }


1 Answers

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 
like image 123
Gus Avatar answered Sep 21 '22 08:09

Gus