If I have two functions like so:
function func1($arg){
function func2(){
}
}
Is there a way to use $arg inside the second function?
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().
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.
func2