get_defined_vars

(PHP 4 >= 4.0.4, PHP 5)

get_defined_vars --  返回由所有已定义变量所组成的数组

描述

array get_defined_vars ( void )

此函数返回一个包含所有已定义变量列表的多维数组,这些变量包括环境变量、服务器变量和用户定义的变量。

<?php
$b
= array(1,1,2,3,5,8);

$arr = get_defined_vars();

// 打印 $b
print_r($arr["b"]);

// 打印 PHP 解释程序的路径(如果 PHP 作为 CGI 使用的话)
// 例如:/usr/local/bin/php
echo $arr["_"];

// 打印命令行参数(如果有的话)
print_r($arr["argv"]);

// 打印所有服务器变量
print_r($arr["_SERVER"]);

// 打印变量数组的所有可用键值
print_r(array_keys(get_defined_vars()));
?>

参见 get_defined_functions()get_defined_constants()


add a note add a note User Contributed Notes
william at avianhosting dot com
04-Nov-2006 04:41
In response to sijmen at digitized dot nl and similar questions -- the problem is variable scope. $GLOBALS is used to access variables in the global scope from inside a function -- this is expected behavior, as get_defined_vars(); is supposed to get the -defined- variables -- and by default, variables in the global scope are -not- defined in the function scope. Therefore, if you want the variables from the global scope -- print_r($GLOBALS);.
zabmilenko at hotmail dot com
01-Sep-2006 10:32
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:

<?php
Array
(
   [
GLOBALS] => Array
       (
           [
GLOBALS] => Array
 *
RECURSION*
           [
_POST] => Array()
           [
_GET] => Array()
           [
_COOKIE] => Array()
           [
_FILES] => Array()
       )

   [
_POST] => 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:

<?php
print '<pre>' . htmlspecialchars(print_r(get_defined_vars(), true)) . '</pre>';
print
'<pre>' . htmlspecialchars(print_r($_SERVER, true)) . '</pre>';
?>

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.
sijmen at digitized dot nl
13-Jul-2004 11:11
I was wondering what the difference was between get_defined_vars() and the array $GLOBALS. If you call get_defined_vars() not from a function, then there is no difference. But, if you call it from inside a function or class, then it will only return the available variables inside that function/class.

- Sijmen Ruwhof
lbowerh at adelphia dot net
05-Jun-2004 11:19
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.

<?php
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

   // Could use a recursive function here. You get the idea ;-)
  
foreach($defined_vars as $key=>$val){
     if(
is_array($val) && !in_array($key,$ignorelist) && count($val) > 0){
      
$message.="\n$key array (key=value):\n";
       foreach(
$val as $subkey=>$subval){
         if(!
in_array($subkey,$ignorelist) && !is_array($subval)){
          
$message.=$subkey." = ".$subval."\n";
         }
         elseif(!
in_array($subkey,$ignorelist) && is_array($subval)){
           foreach(
$subval as $subsubkey=>$subsubval){
             if(!
in_array($subsubkey,$ignorelist)){
              
$message.=$subsubkey." = ".$subsubval."\n";
             }
           }
         }
       }
     }
     elseif(!
is_array($val) && !in_array($key,$ignorelist) && $val){
      
$message.="\nVariable ".$key." = ".$val."\n";
     }
   }

   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";     
     }
   }
}
?>
Ruben Barkow(mail-> at web dot de)
06-May-2004 08:32
this does NOT work:
i tried to find out the name of a variable, that was sent to myfunction($in) with this code:
myfunction($in) {
   $e=array_reverse(get_defined_vars());
   echo "possible name for the variable in the function call: '";
   foreach ($e as $n=>$v){
       if ($v===$in) {
           echo $n;
           break;
       }
   }
   echo"'";
}

but:
get_defined_vars() doesent give back the variables outside of a function.
(the code does work in the main programcode)
php - fw2 - net
30-Dec-2003 07:21
biyectivo, above, is incorrect, at least as of PHP-4.3.3 which does indeed show variables from included/required files, as, IMO, it should. Very useful for debugging foreign code.
biyectivo at hotmail dot com
08-Jun-2003 07:16
Thankfully, get_defined_vars() does NOT return variables which are assigned during an include() call. This would be a big security hole. For example:

//---------------------------------------------------------
include("foo.php");
$var1 = "Hi";

$vars = get_defined_vars();
$ks = array_keys($vars);
  
   for ($i=0;$i<sizeof($ks);$i++)
   {
       echo $ks[$i]." --> ".$vars[$ks[$i]]."< br >";
   }
//---------------------------------------------------------

will return all server variables, then

   var1 --> Hi

but will NOT return

   pwd --> MyPassword

even if inside foo.php there is a line stating

$pwd = "MyPassword";
jgettys at gnuvox dot com
23-Feb-2002 11:09
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';

$z = get_defined_vars();
obj2xml($z['y']);

will output:
<customer id="176C4">
  <name>
   <first>John</first>
   <last>Smith</last>
  </name>
  <arr>
   <Fruit>Bannana</Fruit>
   <Veg>Carrot</Veg>
  </arr>
</customer>