// SCOPE 1
printsmth();
function printsmth(){
// SCOPE 2 (printsmth)
// here (inside SCOPE 2) get variables visible in SCOPE 1
// var_dump($vars);
}
Can I do this?
Essentially I want to get all declared variables from where my function was called, but inside the function (and ignore variables declared in my function)
something like getting the result of get_defined_vars();
, within my function, but for the previous scope :)
Use global
keyword:
$variable = true;
function printsmth(){
global $variable;
if ( $variable ) {
echo 'it works';
}
}
printsmth();
Its so simple
$valriable_Outside_scope;
// SCOPE 1
printsmth();
function printsmth(){
global $valriable_Outside_scope;
// SCOPE 2 (printsmth)
// here (inside SCOPE 2) get variables visible in SCOPE 1
}
global varibale_name ; //will make allow u to access outside scope items
this:
$var = "hello";
printsmth();
function printsmth(){
global $var;
echo $var;
}
You can simply declare variables as global in scope 1 and assign a value to the variables. Further declare the same variable as global in the function body(scope 2) to access it. The above example becomes
// SCOPE 1
global $var1, $var2;
$var1 = 1;
$var2 = 2;
printsmth();
function printsmth(){
global $var1, $var2;
echo 'Var1:' . $var1 . 'Var2:' . $var2;//now accessible in scope 2
}
Another option is that you can pass the variables by reference to the function. For example,
// SCOPE 1
$var1 = 1;
$var2 = 2;
printsmth($var1, $var2);
// Note the "&" appended to the parameters. This passes the variables to the
// function by reference. Any modifications made to the variables will update
// the actual variables in the scope 1
function printsmth(&$var1, &$var2){
global $var1, $var2;
echo 'Var1:' . $var1 . 'Var2:' . $var2;//now accessible in scope 2
}
I know what you are asking. This is not possible in the way you (or I) would like it to be.
You have to pass them in the ways similar to the ways mentioned above. This is how I do it:
function print_smith($globals) {
extract($globals);
echo $variable;
}
$variable = 'Smith';
$vars = get_defined_vars();
printsmith($vars); // Smith
This way is a little cooler (no passing parameters):
function print_smith() {
global $vars;
if(NULL !== $vars) {
extract($vars);
}
echo $variable;
}
$variable = 'Smith';
$vars = get_defined_vars();
printsmith(); // Smith