Jump to content

Nested functions... Why?


Recommended Posts

Hi guys.


I was looking into a way to tidy up my code and i came across the idea of nested functions: a quick google found this:


When you define a function within another function it does not exist until the parent function is executed. Once the parent function has been executed, the nested function is defined and as with any function, accessible from anywhere within the current document. If you have nested functions in your code, you can only execute the outer function once. Repeated calls will try to redeclare the inner functions, which will generate an error.


why would you need nested functions?


any examples of them being used?

Link to comment
Share on other sites

It seems that one advantage is that you could declare the same function in different contexts.


Consider a dynamic function call: $functionname="functionone";


Now if you want, you can call: $functioname(); myecho();


let us say you have defined

function functionone(){
..function myecho(){
....echo "I am one";

function functiontwo(){
..function myecho(){
....echo "I am two";

Now you can call myecho(), and you'll get "i am one". Change the original $functionname to "functiontwo" and the same myecho() call will now spit out "I am two".


Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.