How to access the Variable in inner function PHP? -
how access variable in inner
function of outer
function variable?
i want access $arr
variable in inner function.
<?php function outer() { $arr = array(); function inner($val) { global $arr; if($val > 0) { array_push($arr,$val); } } inner(0); inner(10); inner(20); print_r($arr); } outer();
this kind of "inner function" not expect. global(!) function inner()
defined upon calling outer()
. means, calling outer()
twice results in "cannot redefine inner()" error.
as @hindmost pointed out, need closures, functions can access variables of current scope. also, while normal functions cannot have local scope, closures can, because stored variables.
your code closures:
function outer() { $arr = array(); $inner = function($val) use (&$arr) { if($val > 0) { array_push($arr,$val); } } $inner(0); $inner(10); $inner(20); print_r($arr); } outer();
Comments
Post a Comment