By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Function inside function in PHP

How nested functions work in PHP, including useful example script.

Edited: 2014-10-30 18:39

Q: Is it possible to create a function inside another function in PHP?

Nested functions will not exist before their parent function has been called. Knowing this, you should be able to avoid some common developer mistakes.

Once you have called the parent function, the child function will become accessible anywhere in the script.

Nested function script

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

Accessible anywhere

When the function has been called once, its child functions will be accessible from that point on. The below example demonstrates how to use functions, that are placed inside other functions.

function MyFunc() {

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

}

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

 MyFunc();

 echo DoThis();