Accessing a local variable in a function from an external function (PHP)
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;
}
source to share
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
}
}
source to share
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 ()
source to share