Accessing a local variable in a function from an external function (PHP)

Is there a way to do the following in PHP, or is it just 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?
}

      

+3


source to share


5 answers


Impossible. If $variable

is a global variable, you can access it using a keyword global

. But this is a function. Thus, you cannot access it.

This can be achieved by setting a global variable to an array $GLOBALS

. But again, you are using the global context.



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

function inside() {
        global $variable;
        echo $variable;
}

      

+1


source


note that using the global keyword is impractical since you have no control (you never know where else in your application this variable is used and changed). but if you are using classes it will make things easier.



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

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

    function outside() {
        echo $this->myVar; // anothervalue
    }
}

      

+2


source


No, you cannot access a function's local variable from another function without passing it as an argument.

You can use variables for this global

, but then the variable will not remain local.

+1


source


It's impossible. You can do this using global

. if you just don't want to define parameters but can give it inside a function you can use:

function outside() {
    $variable = 'some value';
    inside(1,2,3);
}

function inside() {
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
    }
}

      

for this see php manual funct_get_args ()

+1


source


You cannot access a local variable in a function. The variable should set the global

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

function inside() {
global $variable;
    echo $variable; 
}

      

It works

0


source







All Articles