By using this site you agree to the use of cookies.

Learn more

Share via:

Nested Functions in PHP

About using nested functions in PHP (functions inside of functions).

Edited: 2017-03-13 15:00

By. Jacob

PHP article image

Nested functions (Aka: functions inside functions) are possible in PHP, but I would personally not recommend it, unless you really need it for something.

I can not think of any cases where it would be useful – but it does not mean that they do not exist. However, you may want to look into Object Oriented PHP instead, since it basically provides the same functionality, and in my opinion, does so cleaner than using plain functional programming.

Nested functions in PHP

When a function is defined inside a parent function, you will first have to call the parent function before the child function becomes available. Once the parent has been called, child functions will be available globally in your PHP script, and not just in the parent.

If you still want to get your hands dirty with nested functions, you should check out the below example:

function MyFunc() {

 // The Nested Functions
 function DoThis() {
  return 'Yeah!';
 }
 function DoThat() {
  return 'Nah!';
 }

}

 // The Main Script
 $string = 'Yes yes';

 MyFunc();

 echo DoThis();

You may also use the nested functions inside of the parent:

function MyFunc($content) {

 // The Nested Functions
 function DoThis() {
  return 'Yeah!';
 }
 function DoThat() {
  return 'Nah!';
 }

 // The Main Function Script
 if ($content == 'Yes yes') {
   return DoThis();
 } else {
   return DoThat();
 }

}

 // The Main Script
 $string = 'Yes yes';

 echo MyFunc($string);

Object-oriented PHP

When we are talking about nested functions, it is hard not to get reminded of OOP. When defining functions (methods) inside of classes in PHP, it is possible to define them using the private and public keywords.

Defining a method as private will only make it usable from within the class it belong to. If the method is defined using public instead, it will be made accessible even outside of the class (I.e. $MyObject->PublicFunction();) which may be useful in many circumstances.

Fore more information on Object-oriented PHP see : PHP Object Oriented Programming Tutorial

Links

  1. User-defined functions - php.net