Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access variable from scope of parent function?

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'
?>
like image 630
JP Lew Avatar asked Dec 05 '11 22:12

JP Lew


People also ask

Can you access a variable inside a function?

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.

How do you access a variable outside a function?

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.

What is the parent of all the scope variable?

Q 23 - $rootScope is the parent of all of the scope variables.

How does var scope work with 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.


1 Answers

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.

like image 189
Wiseguy Avatar answered Sep 21 '22 21:09

Wiseguy