Is there a way to access $foo
from within inner()
?
function outer()
{
$foo = "...";
function inner()
{
// print $foo
}
inner();
}
outer();
First, declare it outside the function, then use it inside the function. You can't access variables declared inside a function from outside a function. The variable belongs to the function's scope only, not the global scope.
Block Level Scope: This scope restricts the variable that is declared inside a specific block, from access by the outside of the block. The let & const keyword facilitates the variables to be block scoped.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
In JavaScript, closures are the primary mechanism used to enable data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can't get at the data from an outside scope except through the object's privileged methods.
PHP<5.3 does not support closures, so you'd have to either pass $foo to inner() or make $foo global from within both outer() and inner() (BAD).
In PHP 5.3, you can do
function outer()
{
$foo = "...";
$inner = function() use ($foo)
{
print $foo;
};
$inner();
}
outer();
outer();
Or am I missing something more complex you are trying to do?
function outer()
{
$foo = "...";
function inner($foo)
{
// print $foo
}
inner($foo);
}
outer();
edit Ok i think i see what you are trying to do. You can do this with classes using global, but not sure about this particular case
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With