downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

get_resource_type> <floatval
Last updated: Thu, 17 Sep 2009

view this page in

get_defined_vars

(PHP 4 >= 4.0.4, PHP 5)

get_defined_vars Devuelve una matriz con todas la variables definidas

Descripción

array get_defined_vars ( void )

Esta función devuelve una matriz multidimensional que contiene una lista de todas las variables definidas, ya sean variables de entorno, de servidor, o definidas por el usuario, al interior del contexto en el que get_defined_vars() es llamado.

Valores retornados

Una matriz multidimensional con todas las variables.

Ejemplos

Example #1 Ejemplo de get_defined_vars()

<?php
$b 
= array(112358);

$matriz get_defined_vars();

// imprimir $b
print_r($matriz["b"]);

/* imprimir ruta al interpretre PHP (si es usado como CGI)
 * p.ej. /usr/local/bin/php */
echo $matriz["_"];

// imprimir los parametros de la linea de comandos, si existen
print_r($matriz["argv"]);

// imprimir todas las variables del servidor
print_r($matriz["_SERVER"]);

// imprimir todas las claves disponibles para las matrices de variables
print_r(array_keys(get_defined_vars()));
?>

Registro de cambios

Versión Descripción
5.0.0 La variable $GLOBALS se incluye en los resultados de la matriz devuelta.

Ver también



get_resource_type> <floatval
Last updated: Thu, 17 Sep 2009
 
add a note add a note User Contributed Notes
get_defined_vars
donovan at example dot com
21-Oct-2008 04:15
As a note, get_defined_vars() does not return a set of variable references (as I hoped). For example:

<?php

// define a variable
$my_var = "foo";

// get our list of defined variables
$defined_vars = get_defined_vars();

// now try to change the value through the returned array
$defined_vars["my_var"] = "bar";

echo
$my_var, "\n";

?>

will output "foo" (the original value). It'd be nice if get_defined_vars() had an optional argument to make them references, but I imagine its a rather specialized request. You can do it yourself (less conveniently) with something like:

<?php

$defined_vars
= array();
$var_names = array_keys(get_defined_vars());

foreach (
$var_names as $var_name)
{
   
$defined_vars[$var_name] =& $$var_name;
}

?>
SyCo
21-Aug-2008 10:52
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 '<p>'.$key.' - '.$value.'</p>';
        }
    }
}

$a=0;
ev($a);
$b=0;
ev($b);
$c=0;
ev($c);
?>
Will output
a - 0

a - 0
b - 0

a - 0
b - 0
c - 0
kailashbadu at hotmail dot com
03-Mar-2007 11:09
After a fruitless attempt find a built-in function whic did this, I wrote this functions to find out all the variables (well, those I wanted) in current scope and their values. I believe this is going to be handy in debugging.

<?php
 
/**
   * @desc   works out the variables in the current scope(from where function was called).
   *         Returns an array with variable name as key and vaiable value as value
   * @param  $varList: variables returned by get_defined_vars() in desired scope.
   *         $excludeList: variables to be excluded from the list.
   * @return array
   */
 
function getDefinedVars($varList, $excludeList)
  {
     
$temp1 = array_values(array_diff(array_keys($varList), $excludeList));
     
$temp2 = array();
      while (list(
$key, $value) = each($temp1)) {
          global $
$value;
         
$temp2[$value] = $$value;
      }
      return
$temp2;
  }
 
 
/**
   * @desc   holds the variable that are to be excluded from the list.
   *         Add or drop new elements as per your preference.
   * @var    array
   */
 
$excludeList = array('GLOBALS', '_FILES', '_COOKIE', '_POST', '_GET', 'excludeList');
 
 
//some dummy variables; add your own or include a file.
 
$firstName = 'kailash';
 
$lastName = 'Badu';
 
$test = array('Pratistha', 'sanu', 'fuchhi');
 
 
//get all variables defined in current scope
 
$varList = get_defined_vars();
 
 
//Time to call the function
 
print "<pre>";
 
print_r(getDefinedVars($varList, $excludeList));
  print
"</pre>";
?>
zabmilenko at hotmail dot com
01-Sep-2006 02: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.
lbowerh at adelphia dot net
05-Jun-2004 03: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";     
      }
    }
}
?>
jgettys at gnuvox dot com
23-Feb-2002 03:09
Simple routine to convert a get_defined_vars object to XML.

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

get_resource_type> <floatval
Last updated: Thu, 17 Sep 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites