I want my function to access an outside variable—from its parent function specifically. However, using the global
keyword sets too broad a scope; I need to limit it. How do I get this code to spit out 'Level 2' instead of 'Level 1'? Do I have to make a class?
<?php
$a = "Level 1";
function first() {
$a = "Level 2";
function second() {
global $a;
echo $a.'<br />';
}
second();
}
first();
//outputs 'Level 1'
?>
Because of how javascript, and most languages, scope variables, 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. Fortunately, functions inherit the scope of their caller.
To access a variable outside a function in JavaScript make your variable accessible from outside the function. 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.
Q 23 - $rootScope is the parent of all of the scope variables.
JavaScript has function scope: Each function creates a new scope. Variables defined inside a function are not accessible (visible) from outside the function. Variables declared with var , let and const are quite similar when declared inside a function.
Just for the sake of example, if I understand what you're trying to do, you could use a closure (PHP 5.3+), as "Closures may also inherit variables from the parent scope" with the use
keyword.
$a = "Level 1";
function first() {
$a = "Level 2";
$func = function () use ($a) {
echo $a.'<br />';
};
$func();
}
first();
// prints 'Level 2<br />'
Closures are most commonly used for callback functions. This may not be the best scenario to use one, however. As others have suggested, just because you can do something doesn't mean it's the best idea.
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