get_defined_vars
This function returns a multidimensional array containing a list of all defined variables, be them environment, server or user-defined variables, within the scope that get_defined_vars() is called.
Parameters
This function has no parameters.
Return Values
A multidimensional array with all the variables.
Examples
Example #1 get_defined_vars() Example
$b = array( 1 , 1 , 2 , 3 , 5 , 8 );
?php
/* print path to the PHP interpreter (if used as a CGI)
* e.g. /usr/local/bin/php */
echo $arr [ «_» ];
// print the command-line parameters if any
print_r ( $arr [ «argv» ]);
// print all the server vars
print_r ( $arr [ «_SERVER» ]);
// print all the available keys for the arrays of variables
print_r ( array_keys ( get_defined_vars ()));
?>
See Also
- isset() — Determine if a variable is declared and is different than null
- get_defined_functions() — Returns an array of all defined functions
- get_defined_constants() — Returns an associative array with the names of all the constants and their values
User Contributed Notes 20 notes
Be aware of what get_defined_vars() function returns in different contexts:
— In global scope, a list of all defined variables, whether superglobals, command line arguments or user-defined variables
— In function scope, only a list of user-defined variables (both arguments and in-body definitions)
— In class/object method scope, does not return class/object properties;
Also, as of PHP 5.4, does not return $_ENV even where available.
For further details and scope tests/results, see https://github.com/php/doc-en/issues/1317
NOTE: when you call code by eval() PHP append self vars to result, they have «__» prefix («__source_code» and «__bootstrap_file» in PHP 7.3).
Fix:
function filter_eval_vars (array $vars ): array
foreach ( $vars as $key => $value ) if ( $key [ 0 ] === ‘_’ && $key [ 1 ] === ‘_’ ) unset( $vars [ $key ]);
>
>
return $vars ;
>
get_defined_vars() is very useful for importing many values at once
into another scope (Such as User-defined functions).
Below is an example for showing some of many values and their variable-names in a table.
(useful in debugging)
You can put this user-defined function at many places in your script
to show some values (values to be changed in loops)
to check if they are what they shall be there or not.
// Set «get_defined_vars()» to 2nd argument.
function get_value_table ( $name_array , $gdv ) $name_value_table = [];
foreach ( $name_array as $name ) :
if (! array_key_exists ( $name , $gdv )) :
$value = ‘undefined’ ;
elseif ( is_bool ( $gdv [ $name ])) :
$value = $gdv [ $name ]? ‘true’ : ‘false’ ;
elseif ( is_numeric ( $gdv [ $name ]) || is_string ( $gdv [ $name ])) :
$value = $gdv [ $name ];
elseif ( is_array ( $gdv [ $name ])) :
$value = ‘
' . print_r ( $gdv [ $name ], true ). '
‘ ;
else :
$value = ( PHP_VERSION_ID >= 80000 )? get_debug_type ( $gdv [ $name ]) : get_type ( $gdv [ $name ]);
endif;
$name_value_table [] = ‘$’ . $name . » . $value ;
endforeach;
return ‘
‘ ;
> // (f) get_value_table()
$_1 = ‘a’ ;
$_2 = ‘b’ ;
$_3 = [ 1 , 2 ];
$_4 = false ;
$_5 = null ;
$name_array = [ ‘_1’ , ‘_2’ , ‘_3’ , ‘_4’ , ‘_5’ , ‘_6’ ];
$show_id = 1 ;
if ( $show_id === 1 ) :
echo get_value_table ( $name_array , get_defined_vars ());
endif;
/*
if $show_id === 1, only shows below.
$_2 = ‘c’ ;
if ( $show_id === 2 ) :
echo get_value_table ( $name_array , get_defined_vars ()); // $_2 c
endif;
# if $show_id === 2, $_2 turns «c».
Since get_defined_vars() only gets the variables at the point you call the function, there is a simple way to get the variables defined within the current scope.
// The very top of your php script
$vars = get_defined_vars ();
// Now do your stuff
$foo = ‘foo’ ;
$bar = ‘bar’ ;
// Get all the variables defined in current scope
$vars = array_diff ( get_defined_vars (), $vars );
echo ‘
' ;
print_r ( $vars );
echo '
‘ ;
?>
A little gotcha to watch out for:
If you turn off RegisterGlobals and related, then use get_defined_vars(), you may see something like the following:
Array
(
[ GLOBALS ] => Array
(
[ GLOBALS ] => Array
* RECURSION *
[ _POST ] => Array()
[ _GET ] => Array()
[ _COOKIE ] => Array()
[ _FILES ] => Array()
)
[ _GET ] => Array()
[ _COOKIE ] => Array()
[ _FILES ] => Array()
)
?>
Notice that $_SERVER isn’t there. It seems that php only loads the superglobal $_SERVER if it is used somewhere. You could do this:
print ‘
' . htmlspecialchars ( print_r ( get_defined_vars (), true )) . '
‘ ;
print ‘
' . htmlspecialchars ( print_r ( $_SERVER , true )) . '
‘ ;
?>
And then $_SERVER will appear in both lists. I guess it’s not really a gotcha, because nothing bad will happen either way, but it’s an interesting curiosity nonetheless.
Insert this at point of interest; add keys of unwanted 1st dim variables to 2nd param of array_diff_key
echo ‘
defined_except ' ; var_dump ( array_diff_key ( get_defined_vars (), [ 'GLOBALS' => 0 , '_SERVER' => 0 ])); echo ' ' . basename ( __FILE__ ). ':' . __LINE__ . '
‘ ; #die;
?>
Reference variables are returned by reference (tested on PHP 5.5.11):
$a = null ;
$b = & $a ;
get_defined_vars ()[ ‘b’ ] = 4 ;
var_dump ( $b ); // int(4)
?>
get_defined_vars() returns all variables — locally defined vars and global vars (well actually only super globals). If you need local vars only — for example you need to get variables from a file — let’s say config.php and you don’t want a missing value to be replaced with a global defined somewhere else.
/**
* Filters out global vars from get_defined_vars() in order to get local vars only
* @param array $localVars pass get_defined_vars() here
*
* @return array local vars only
*/
function removeGlobals (array $localVars ) return array_diff_key ( $localVars , $GLOBALS );
>
define ( ‘CONFIG_FILE_PATH’ , ‘/path/to/config.php’ );
function readConfig () require CONFIG_FILE_PATH ;
$config = removeGlobals ( get_defined_vars ());
return $config ;
>
Here is a function which generates a debug report for display or email
using get_defined_vars. Great for getting a detailed snapshot without
relying on user input.
function generateDebugReport ( $method , $defined_vars , $email = «undefined» ) // Function to create a debug report to display or email.
// Usage: generateDebugReport(method,get_defined_vars(),email[optional]);
// Where method is «browser» or «email».
// Create an ignore list for keys returned by ‘get_defined_vars’.
// For example, HTTP_POST_VARS, HTTP_GET_VARS and others are
// redundant (same as _POST, _GET)
// Also include vars you want ignored for security reasons — i.e. PHPSESSID.
$ignorelist =array( «HTTP_POST_VARS» , «HTTP_GET_VARS» ,
«HTTP_COOKIE_VARS» , «HTTP_SERVER_VARS» ,
«HTTP_ENV_VARS» , «HTTP_SESSION_VARS» ,
«_ENV» , «PHPSESSID» , «SESS_DBUSER» ,
«SESS_DBPASS» , «HTTP_COOKIE» );
$timestamp = date ( «m/d/y h:m:s» );
$message = «Debug report created $timestamp \n» ;
// Get the last SQL error for good measure, where $link is the resource identifier
// for mysql_connect. Comment out or modify for your database or abstraction setup.
global $link ;
$sql_error = mysql_error ( $link );
if( $sql_error ) $message .= «\nMysql Messages:\n» . mysql_error ( $link );
>
// End MySQL
if( $method == «browser» ) echo nl2br ( $message );
>
elseif( $method == «email» ) if( $email == «undefined» ) $email = $_SERVER [ «SERVER_ADMIN» ];
>
$mresult = mail ( $email , «Debug Report for » . $_ENV [ «HOSTNAME» ]. «» , $message );
if( $mresult == 1 ) echo «Debug Report sent successfully.\n» ;
>
else echo «Failed to send Debug Report.\n» ;
>
>
>
?>
I occasionally use this as a hack to convert arguments to an array where terseness is needed (dealing with legacy code, etc).
However in an object context it’ll also pull in $this.
Make sure to unset it. If you map it to properties or an array then setting the key this wont be an error.
I recommend using a wrapper function that strips this from the result.
for all those who don’t know how to us this function. copy and run this code in your computer .
note: you need to know what superglobals are.
$A = 5 ;
$B = 10 ;
$C = 15 ;
$D = 20 ;
var_dump ( $F ); //don’t use echo. it will show error
?>
Result : will show all superglobals status along with your defined
variables along with its values
Simple routine to convert a get_defined_vars object to XML.
function obj2xml ( $v , $indent = » ) <
while (list( $key , $val ) = each ( $v )) <
if ( $key == ‘__attr’ ) continue;
// Check for __attr
if ( is_object ( $val -> __attr )) <
while (list( $key2 , $val2 ) = each ( $val -> __attr )) <
$attr .= » $key2 =\» $val2 \»» ;
>
>
else $attr = » ;
if ( is_array ( $val ) || is_object ( $val )) <
print( » $indent < $key$attr >\n» );
obj2xml ( $val , $indent . ‘ ‘ );
print( » $indent$key> \n» );
>
else print( » $indent < $key$attr >$val$key> \n» );
>
>
//Example object
$x -> name -> first = «John» ;
$x -> name -> last = «Smith» ;
$x -> arr [ ‘Fruit’ ] = ‘Bannana’ ;
$x -> arr [ ‘Veg’ ] = ‘Carrot’ ;
$y -> customer = $x ;
$y -> customer -> __attr -> id = ‘176C4’ ;
Here’s a very simple function for debugging. It’s far from perfect but I find it very handy. It outputs the var value and the var name on a new line. The problem is it’ll echo any vars and their name if they share the same value. No big deal when debugging and saves the hassle of writing the HTML and var name when echoing a variable. (ev=echo variable). Using get_defined_vars() inside a function renames the var name to the functions variable so isn’t as useful for debugging. Of course, you’ll need access to the $GLOBALS array
function ev($variable) foreach($GLOBALS as $key => $value) if($variable===$value) echo ‘
‘.$key.’ — ‘.$value.’
‘;
>
>
>
PHP Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
Global and Local Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
Example
Variable with global scope:
function myTest() // using x inside this function will generate an error
echo «
Variable x inside function is: $x
«;
>
myTest();
echo «
Variable x outside function is: $x
«;
?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:
Example
Variable with local scope:
function myTest() $x = 5; // local scope
echo «
Variable x inside function is: $x
«;
>
myTest();
?php
// using x outside the function will generate an error
echo «
Variable x outside function is: $x
«;
?>
You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.
PHP The global Keyword
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
Example
function myTest() global $x, $y;
$y = $x + $y;
>
myTest();
echo $y; // outputs 15
?>
PHP also stores all global variables in an array called $GLOBALS[index] . The index holds the name of the variable. This array is also accessible from within functions and can be used to update global variables directly.
The example above can be rewritten like this:
Example
function myTest() $GLOBALS[‘y’] = $GLOBALS[‘x’] + $GLOBALS[‘y’];
>
myTest();
echo $y; // outputs 15
?>
PHP The static Keyword
Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
Example
Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.
Note: The variable is still local to the function.