Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access local variable in function from outside function (PHP)

Tags:

php

Is there a way to achieve the following in PHP, or is it simply not allowed? (See commented line below)

function outside() {
    $variable = 'some value';
    inside();
}

function inside() {
    // is it possible to access $variable here without passing it as an argument?
}
like image 466
hsdev Avatar asked Mar 10 '12 12:03

hsdev


People also ask

Can local variables be accessed outside the function?

Variables declared inside any function with var keyword are called local variables. Local variables cannot be accessed or modified outside the function declaration.

How do you use variables 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.


2 Answers

note that using the global keyword is not advisable, as you have no control (you never know where else in your app the variable is used and altered). but if you are using classes, it'll make things a lot easier!

class myClass {
    var $myVar = 'some value';

    function inside() {
        $this->myVar = 'anothervalue';
        $this->outside(); // echoes 'anothervalue'
    }

    function outside() {
        echo $this->myVar; // anothervalue
    }
}
like image 75
giorgio Avatar answered Nov 06 '22 22:11

giorgio


Its not possible. If $variable is a global variable you could have access it by global keyword. But this is in a function. So you can not access it.

It can be achieved by setting a global variable by$GLOBALS array though. But again, you are utilizing the global context.

function outside() {
    $GLOBALS['variable'] = 'some value';
    inside();
}

function inside() {
        global $variable;
        echo $variable;
}
like image 24
Shiplu Mokaddim Avatar answered Nov 06 '22 21:11

Shiplu Mokaddim