Var dump php что это

от admin

var_dump

This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.

All public, private and protected properties of objects will be returned in the output unless the object implements a __debugInfo() method (implemented in PHP 5.6.0).

As with anything that outputs its result directly to the browser, the output-control functions can be used to capture the output of this function, and save it in a string (for example).

var_dump

Функция отображает структурированную информацию об одном или нескольких выражениях, включая их тип и значение. Массивы и объекты анализируются рекурсивно с разным отступом у значений для визуального отображения структуры.

Все общедоступные, закрытые и защищённые свойства объекта будут возвращены при выводе, если только объект не реализует метод __debugInfo().

Как и с любой другой функцией, осуществляющей вывод непосредственно в браузер, вы можете использовать функции контроля вывода, чтобы перехватывать выводимые этой функцией данные и сохранять их, например, в строку ( string ).

Список параметров

Выражение, которое необходимо отобразить.

Следующие выражения для отображения.

Возвращаемые значения

Функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример использования var_dump()

Результат выполнения данного примера:

$b = 3.1 ;
$c = true ;
var_dump ( $b , $c );

Результат выполнения данного примера:

Смотрите также

  • print_r() — Выводит удобочитаемую информацию о переменной
  • debug_zval_dump() — Выводит строковое представление внутренней структуры zval
  • var_export() — Выводит или возвращает интерпретируемое строковое представление переменной

User Contributed Notes 16 notes

Keep in mind if you have xdebug installed it will limit the var_dump() output of array elements and object properties to 3 levels deep.

To change the default, edit your xdebug.ini file and add the folllowing line:
xdebug.var_display_max_depth=n

If you’re like me and uses var_dump whenever you’re debugging, you might find these two «wrapper» functions helpful.

This one automatically adds the PRE tags around the var_dump output so you get nice formatted arrays.

function var_dump_pre ( $mixed = null ) <
echo ‘<pre>’ ;
var_dump ( $mixed );
echo ‘</pre>’ ;
return null ;
>

?>

This one returns the value of var_dump instead of outputting it.

function var_dump_ret ( $mixed = null ) <
ob_start ();
var_dump ( $mixed );
$content = ob_get_contents ();
ob_end_clean ();
return $content ;
>

?>

Fairly simple functions, but they’re infinitely helpful (I use var_dump_pre() almost exclusively now).

I post a new var_dump function with colors and collapse features. It can also adapt to terminal output if you execute it from there. No need to wrap it in a pre tag to get it to work in browsers.

<?php
function dump_debug ( $input , $collapse = false ) <
$recursive = function( $data , $level = 0 ) use (& $recursive , $collapse ) <
global $argv ;

$isTerminal = isset( $argv );

if (! $isTerminal && $level == 0 && ! defined ( «DUMP_DEBUG_SCRIPT» )) <
define ( «DUMP_DEBUG_SCRIPT» , true );

echo ‘<script language=»Javascript»>function toggleDisplay(id) <' ;
echo ‘var state = document.getElementById(«container»+id).style.display;’ ;
echo ‘document.getElementById(«container»+id).style.display = state == «inline» ? «none» : «inline»;’ ;
echo ‘document.getElementById(«plus»+id).style.display = state == «inline» ? «inline» : «none»;’ ;
echo ‘></script>’ . «\n» ;
>

$type = ! is_string ( $data ) && is_callable ( $data ) ? «Callable» : ucfirst ( gettype ( $data ));
$type_data = null ;
$type_color = null ;
$type_length = null ;

switch ( $type ) <
case «String» :
$type_color = «green» ;
$type_length = strlen ( $data );
$type_data = «\»» . htmlentities ( $data ) . «\»» ; break;

case «Double» :
case «Float» :
$type = «Float» ;
$type_color = «#0099c5» ;
$type_length = strlen ( $data );
$type_data = htmlentities ( $data ); break;

case «Integer» :
$type_color = «red» ;
$type_length = strlen ( $data );
$type_data = htmlentities ( $data ); break;

case «Boolean» :
$type_color = «#92008d» ;
$type_length = strlen ( $data );
$type_data = $data ? «TRUE» : «FALSE» ; break;

case «NULL» :
$type_length = 0 ; break;

case «Array» :
$type_length = count ( $data );
>

if ( in_array ( $type , array( «Object» , «Array» ))) <
$notEmpty = false ;

foreach( $data as $key => $value ) <
if (! $notEmpty ) <
$notEmpty = true ;

if ( $isTerminal ) <
echo $type . ( $type_length !== null ? «(» . $type_length . «)» : «» ). «\n» ;

> else <
$id = substr ( md5 ( rand (). «:» . $key . «:» . $level ), 0 , 8 );

echo «<a href=\»javascript:toggleDisplay(‘» . $id . «‘);\» style=\»text-decoration:none\»>» ;
echo «<span style=’color:#666666′>» . $type . ( $type_length !== null ? «(» . $type_length . «)» : «» ) . «</span>» ;
echo «</a>» ;
echo «<span > . $id . «\» style=\»display: » . ( $collapse ? «inline» : «none» ) . «;\»>&nbsp;&#10549;</span>» ;
echo «<div > . $id . «\» style=\»display: » . ( $collapse ? «» : «inline» ) . «;\»>» ;
echo «<br />» ;
>

for ( $i = 0 ; $i <= $level ; $i ++) <
echo $isTerminal ? «| » : «<span style=’color:black’>|</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;» ;
>

for ( $i = 0 ; $i <= $level ; $i ++) <
echo $isTerminal ? «| » : «<span style=’color:black’>|</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;» ;
>

echo $isTerminal ? «[» . $key . «] => » : «<span style=’color:black’>[» . $key . «]&nbsp;=>&nbsp;</span>» ;

call_user_func ( $recursive , $value , $level + 1 );
>

if ( $notEmpty ) <
for ( $i = 0 ; $i <= $level ; $i ++) <
echo $isTerminal ? «| » : «<span style=’color:black’>|</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;» ;
>

> else <
echo $isTerminal ?
$type . ( $type_length !== null ? «(» . $type_length . «)» : «» ) . » » :
«<span style=’color:#666666′>» . $type . ( $type_length !== null ? «(» . $type_length . «)» : «» ) . «</span>&nbsp;&nbsp;» ;
>

> else <
echo $isTerminal ?
$type . ( $type_length !== null ? «(» . $type_length . «)» : «» ) . » » :
«<span style=’color:#666666′>» . $type . ( $type_length !== null ? «(» . $type_length . «)» : «» ) . «</span>&nbsp;&nbsp;» ;

if ( $type_data != null ) <
echo $isTerminal ? $type_data : «<span style=’color:» . $type_color . «‘>» . $type_data . «</span>» ;
>
>

call_user_func ( $recursive , $input );
>
?>

As Bryan said, it is possible to capture var_dump() output to a string. But it’s not quite exact if the dumped variable contains HTML code.

You can use this instead:

<?php
echo ‘<pre>’ ; // This is for correct handling of newlines
ob_start ();
var_dump ( $var );
$a = ob_get_contents ();
ob_end_clean ();
echo htmlspecialchars ( $a , ENT_QUOTES ); // Escape every HTML special chars (especially > and < )
echo ‘</pre>’ ;
?>

<?php
/**
* Better GI than print_r or var_dump — but, unlike var_dump, you can only dump one variable.
* Added htmlentities on the var content before echo, so you see what is really there, and not the mark-up.
*
* Also, now the output is encased within a div block that sets the background color, font style, and left-justifies it
* so it is not at the mercy of ambient styles.
*
* Inspired from: PHP.net Contributions
* Stolen from: [highstrike at gmail dot com]
* Modified by: stlawson *AT* JoyfulEarthTech *DOT* com
*
* @param mixed $var — variable to dump
* @param string $var_name — name of variable (optional) — displayed in printout making it easier to sort out what variable is what in a complex output
* @param string $indent — used by internal recursive call (no known external value)
* @param unknown_type $reference — used by internal recursive call (no known external value)
*/
function do_dump (& $var , $var_name = NULL , $indent = NULL , $reference = NULL )
<
$do_dump_indent = «<span style=’color:#666666;’>|</span> &nbsp;&nbsp; » ;
$reference = $reference . $var_name ;
$keyvar = ‘the_do_dump_recursion_protection_scheme’ ; $keyname = ‘referenced_object_name’ ;

Читать:
Зависла программа 1с что делать

// So this is always visible and always left justified and readable
echo «<div style=’text-align:left; background-color:white; font: 100% monospace; color:black;’>» ;

if ( is_array ( $var ) && isset( $var [ $keyvar ]))
<
$real_var = & $var [ $keyvar ];
$real_name = & $var [ $keyname ];
$type = ucfirst ( gettype ( $real_var ));
echo » $indent$var_name <span style=’color:#666666′> $type </span> = <span style=’color:#e87800;’>&amp; $real_name </span><br>» ;
>
else
<
$var = array( $keyvar => $var , $keyname => $reference );
$avar = & $var [ $keyvar ];

$type = ucfirst ( gettype ( $avar ));
if( $type == «String» ) $type_color = «<span style=’color:green’>» ;
elseif( $type == «Integer» ) $type_color = «<span style=’color:red’>» ;
elseif( $type == «Double» )< $type_color = "<span style='color:#0099c5'>" ; $type = "Float" ; >
elseif( $type == «Boolean» ) $type_color = «<span style=’color:#92008d’>» ;
elseif( $type == «NULL» ) $type_color = «<span style=’color:black’>» ;

if( is_array ( $avar ))
<
$count = count ( $avar );
echo » $indent » . ( $var_name ? » $var_name => » : «» ) . «<span style=’color:#666666′> $type ( $count )</span><br> $indent (<br>» ;
$keys = array_keys ( $avar );
foreach( $keys as $name )
<
$value = & $avar [ $name ];
do_dump ( $value , «[‘ $name ‘]» , $indent . $do_dump_indent , $reference );
>
echo » $indent )<br>» ;
>
elseif( is_object ( $avar ))
<
echo » $indent$var_name <span style=’color:#666666′> $type </span><br> $indent (<br>» ;
foreach( $avar as $name => $value ) do_dump ( $value , » $name » , $indent . $do_dump_indent , $reference );
echo » $indent )<br>» ;
>
elseif( is_int ( $avar )) echo » $indent$var_name = <span style=’color:#666666′> $type (» . strlen ( $avar ). «)</span> $type_color » . htmlentities ( $avar ). «</span><br>» ;
elseif( is_string ( $avar )) echo » $indent$var_name = <span style=’color:#666666′> $type (» . strlen ( $avar ). «)</span> $type_color \»» . htmlentities ( $avar ). «\»</span><br>» ;
elseif( is_float ( $avar )) echo » $indent$var_name = <span style=’color:#666666′> $type (» . strlen ( $avar ). «)</span> $type_color » . htmlentities ( $avar ). «</span><br>» ;
elseif( is_bool ( $avar )) echo » $indent$var_name = <span style=’color:#666666′> $type (» . strlen ( $avar ). «)</span> $type_color » .( $avar == 1 ? «TRUE» : «FALSE» ). «</span><br>» ;
elseif( is_null ( $avar )) echo » $indent$var_name = <span style=’color:#666666′> $type (» . strlen ( $avar ). «)</span> < $type_color >NULL</span><br>» ;
else echo » $indent$var_name = <span style=’color:#666666′> $type (» . strlen ( $avar ). «)</span> » . htmlentities ( $avar ). «<br>» ;

Var dump php что это

Debugging is as important as coding in the field of development. There might occur a case when the developer needs to check information of a variable such as if a function returns an array it is best to check the return type and the contents of the returned value. A developer may echo all the contents but PHP itself provides a method to do the same and as well as checks the datatype.

The var_dump() function is used to dump information about a variable. This function displays structured information such as type and value of the given variable. Arrays and objects are explored recursively with values indented to show structure. This function is also effective with expressions.

Syntax:

Parameters: The function takes a single argument $expsn that may be one single variable or an expression containing several space separated variables of any type.

Return Type: This function has no return type.
Examples:

PHP var_dump

Summary: in this tutorial, you will learn how to use the PHP var_dump() function to dump the information about a variable.

Introduction to the PHP var_dump function

The var_dump() is a built-in function that allows you to dump the information about a variable. The var_dump() function accepts a variable and displays its type and value.

Suppose that you have a variable called $balance with a value of 100 :

To display the information of the $balance variable, you place it within parentheses that follow the var_dump function name like this:

If you open the page on the web browser, you’ll see the following output:

The output shows the value of the variable (100) and its type (int) which stands for integer.

The following shows how to dump information about two variables $amount and $message :

To make the output more intuitive, you can wrap the output of the var_dump() function in a pre tag like this:

The output now is much more readable.

The dump helper function

It’s kind of tedious to always echo the opening <pre> and closing </pre> tags when you dump the information about the variable.

To make it easier, you can define a function and reuse it. For now, you can think that a function is a reusable piece of code that can be referenced by a name. A function may have input and also output.

PHP has many built-in functions like var_dump() . It also allows you to define your own functions. These functions are called user-defined functions. And you’ll learn more about it in the function tutorial.

The following defines a function called d() that accepts a variable. It shows the information about the variable and wraps the output in the <pre> tag:

To use the d() function, you can pass a variable to it as follows:

The output is much cleaner now.

Dump and die using the var_dump() and die() functions

The die() function displays a message and terminates the execution of the script:

Sometimes, you want to dump the information of a variable and terminate the script immediately. In this case, you can combine the var_dump() function with the die() function as follows:

  • First, dump the information about the $message variable using the var_dump() function.
  • Second, terminate the script immediately by calling the die() function.

Since the die() function terminates the script immediately, the following statement did not execute:

Therefore, you didn’t see the message in the output.

To make the code reusable, you can wrap the code snippet above in a function e.g., dd() . The name dd stands for the dump and die:

Now, you can use the dd() function as follows:

In the later tutorial, you will learn how to place the functions in a file and reuse them in any script.

Похожие статьи