0

If I have two functions like so:

function func1($arg){
  function func2(){
  }
}

Is there a way to use $arg inside the second function?

1
  • you can simply put the $arg in func2 Commented Mar 1, 2014 at 14:50

3 Answers 3

1

You can use the same argument inside the nested function, but I would not recommend doing it. It will get messy sooner. The best practice would be to define the function outside and then use it wherever you want. If the function does a task that's not repeated frequently, then why do you have a nested function in the first place? Place all the logic inside the first function itself and do whatever you need.

If you're using PHP 5.3+, you can make use of the Lambda functions. For example, to sum two input variables, it can be written as:

function some_func($a) {
    return function($b) use ($a) {
        return sum($a, $b);
    }
}

If that's not an option and you're okay with nested functions and the problems that come from using it, then you can do the following:

function func1($arg) {
    function func2($arg) {
        # code...
    }
}

If your function has to accept multiple parameters, then you might use func_get_args() and / or func_num_args().

Sign up to request clarification or add additional context in comments.

Comments

1

This is not advised, try to keep your functions as small as possible / don't nest functions or too many statements. You also might need func2 elsewhere.

If you want the args for the 2nd function, you will have to pass them as parameters for the function; func2($arg). Would be stupid to globalize variables or save them in a session.

Comments

0

Yes. You need to separate your functions and if you want to call function 2 inside of function 1 you would do like so :

function func1($arg){
//write some code
    func2($arg);
}

function func2($arg2){
//write some more code
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.