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

search for in the

웹 서비스> <var_dump
Last updated: Fri, 24 Jul 2009

view this page in

var_export

(PHP 4 >= 4.2.0, PHP 5)

var_export변수를 처리가능한 문자열 표현으로 출력하거나 반환합니다

설명

mixed var_export ( mixed $expression [, bool $return ] )

var_export()는 주어진 변수에 대한 구조화된 정보를 얻습니다. 한 가지 차이를 제외하고, var_dump()와 동일합니다: 반환된 표현은 유효한 PHP 코드입니다.

인수

expression

내보내길 원하는 변수

return

TRUE로 설정하여 사용하면, var_export()는 변수 표현을 출력하는 대신에 반환합니다.

Note: 이 함수를 특정 인수와 함께 사용할 때, 내부적으로 출력 버퍼링을 사용합니다. 그러므로, ob_start() 콜백 함수 안에서는 사용할 수 없습니다.

반환값

return 인수를 TRUE로 사용할 때 변수 표현을 반환합니다. 그 외에는 NULL을 반환합니다.

변경점

버전 설명
5.1.0 __set_state 마법 메쏘드를 사용하여 클래스와 클래스를 가진 배열을 내보낼 수 있게 되었습니다.

예제

Example #1 var_export() 예제

<?php
$a 
= array (12, array ("a""b""c"));
var_export($a);
?>

위 예제의 출력:

array (
  0 => 1,
  1 => 2,
  2 => 
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)
<?php
$b 
3.1;
$v var_export($btrue);
echo 
$v;
?>

위 예제의 출력:

3.1

Example #2 PHP 5.1.0부터 클래스 내보내기

<?php
class { public $var; }
$a = new A;
$a->var 5;
var_export($a);
?>

위 예제의 출력:

A::__set_state(array(
    'var' => 5,
))

Example #3 __set_state 사용하기 (PHP 5.1.0부터)

<?php
class A
{
    public 
$var1;
    public 
$var2;

    public static function 
__set_state($an_array)
    {
        
$obj = new A;
        
$obj->var1 $an_array['var1'];
        
$obj->var2 $an_array['var2'];
        return 
$obj;
    }
}

$a = new A;
$a->var1 5;
$a->var2 'foo';

eval(
'$b = ' var_export($atrue) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);
?>

위 예제의 출력:

object (A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}

주의

Note: 이 함수로 resource형 변수는 내보낼 수 없습니다.

Note: var_export()는 순환 참조를 다루지 못합니다. 처리 가능한 PHP 코드를 생성하는 것이 불가능에 가깝기 때문입니다. 배열이나 객체로 그러한 일을 하려면, serialize()를 사용하십시오.

참고

  • print_r() - 변수에 관한 정보를 사람이 읽기 편하게 출력
  • serialize() - 값의 저장 표현을 생성
  • var_dump() - 변수에 대한 정보를 덤프



웹 서비스> <var_dump
Last updated: Fri, 24 Jul 2009
 
add a note add a note User Contributed Notes
var_export
rarioj at gmail dot com
29-Oct-2009 03:43
NOTE: If an object Foo has __set_state() method, but if that object contains another object Bar with no __set_state() method implemented, the resulting PHP expression will not be eval()-able.

This is an example (object Test that contains an instance of Exception).

<?php

class Test
{
  public
$one;
  public
$two;
  public function
__construct($one, $two)
  {
   
$this->one = $one;
   
$this->two = $two;
  }
  public static function
__set_state(array $array)
  {
    return new
self($array['one'], $array['two']);
  }
}

$test = new Test('one', new Exception('test'));

$string = var_export($test, true);

/* $string =
Test::__set_state(array(
   'one' => 'one',
   'two' =>
  Exception::__set_state(array(
     'message' => 'test',
     'string' => '',
     'code' => 0,
     'file' => 'E:\\xampp\\htdocs\\test.Q.php',
     'line' => 35,
     'trace' =>
    array (
    ),
     'previous' => NULL,
  )),
))
*/

eval('$test2 = '.$string.';'); // Fatal error: Call to undefined method Exception::__set_state

?>

So avoid using var_export() on a complex array/object that contains other objects. Instead, use serialize() and unserialize() functions.

<?php

$string
= 'unserialize('.var_export(serialize($test), true).')';

eval(
'$test2 = '.$string.';');

var_dump($test == $test2); // bool(true)

?>
ravenswd at gmail dot com
08-Jul-2009 02:32
(This replaces my note of 3-July-2009. The original version produced no output if a variable contained an empty array, or an array consisting only of empty arrays. For example, $bigarray['x'] = array(); Also, I have added a second version of the function.)

The output can be difficult to decipher when looking at an array with many levels and many elements on each level. For example:

<?php
print ('$bigarray = ' . var_export($bigarray, true) . "\n");
?>

will return:

$bigarray = array(
... (500 lines skipped) ...
          'mod' => 'charlie',

Whereas the routine below can be called with:

<?php
recursive_print
('$bigarray', $bigarray);
?>

and it will return:

$bigarray = array()
... (500 lines skipped) ...
$bigarray['foo']['bar']['0']['somethingelse']['mod'] = 'charlie'

Here's the function:

<?php
function recursive_print ($varname, $varval) {
  if (!
is_array($varval)):
    print
$varname . ' = ' . $varval . "<br>\n";
  else:
    print
$varname . " = array()<br>\n";
    foreach (
$varval as $key => $val):
     
recursive_print ($varname . "['" . $key . "']", $val);
    endforeach;
  endif;
}
?>

For those who want a version that produces valid PHP code, use this version:

<?php
function recursive_print ($varname, $varval) {
  if (!
is_array($varval)):
    print
$varname . ' = ' . var_export($varval, true) . ";<br>\n";
  else:
    print
$varname . " = array();<br>\n";
    foreach (
$varval as $key => $val):
     
recursive_print ($varname . "[" . var_export($key, true) . "]", $val);
    endforeach;
  endif;
}
?>

If your output is to a text file and not an HTML page, remove the <br>s.
ravenswd at gmail dot com
03-Jul-2009 09:21
The output can be difficult to decipher when looking at an array with many levels and many elements on each level. For example:

<?php
print ('$bigarray = ' . var_export($bigarray, true) . "\n");
?>

will return:

$bigarray = array(
... (500 lines skipped) ...
          'mod' => 'charlie',

Whereas the routine below can be called with:

<?php
recursive_print
('$bigarray', $bigarray);
?>

and it will return:

$bigarray['firstelement'] = 'something'
... (500 lines skipped) ...
$bigarray['foo']['bar']['0']['somethingelse']['mod'] = 'charlie'

Here's the function:

<?php
function recursive_print ($varname, $varval) {
  if (!
is_array($varval)):
    print
$varname . ' = ' . $varval . "<br>\n";
  else:
    foreach (
$varval as $key => $val):
     
recursive_print ($varname . "['" . $key . "']", $val);
    endforeach;
  endif;
}
?>
cmusicfan (at) gmail (daught) com
12-Jun-2009 01:19
Caution! var_export will add a backslash to single quotes (').

You may want to use stripslashes() to remove the mysteriously added backslashes.
stangelanda at arrowquick dot com
30-Jun-2007 08:20
I have been looking for the best method to store data in cache files.

First, I've identified two limitations of var_export verus serialize.  It can't store internal references inside of an array and it can't store a nested object or an array containing objects before PHP 5.1.0.

However, I could deal with both of those so I created a benchmark.  I used a single array containing from 10 to 150 indexes.  I've generate the elements' values randomly using booleans, nulls, integers, floats, and some nested arrays (the nested arrays are smaller averaging 5 elements but created similarly).  The largest percentage of elements are short strings around 10-15 characters.  While there is a small number of long strings (around 500 characters).

Benchmarking returned these results for 1000 * [total time] / [iterations (4000 in this case)]

serialize 3.656, 3.575, 3.68, 3.933, mean of 3.71
include 7.099, 5.42, 5.185, 6.076, mean of 5.95
eval 5.514, 5.204, 5.011, 5.788, mean of 5.38

Meaning serialize is around 1 and a half times faster than var_export for a single large array.  include and eval were consistently very close but eval was usually a few tenths faster (eval did better this particular set of trials than usual). An opcode cache like APC might make include faster, but otherwise serialize is the best choice.
Glen
24-May-2007 09:47
Like previously reported, i find var_export() frustrating when dealing with recursive structures.  Doing a :

<?php
var_export
($GLOBALS);
?>

fails.  Interestingly, var_dump() has some logic to avoid recursive references.  So :

<?php
var_dump
($GLOBALS);
?>

works (while being more ugly).  Unlike var_export(), var_dump() has no option to return the string, so output buffering logic is required if you want to direct the output.
niq
21-Mar-2007 10:44
To import exported variable you can use this code:

<?
$str
=file_get_contents('exported_var.str');
$var=eval('return '.$str.';')
// Now $val contains imported variable
?>
dosperios at dot gmail dot nospam do com
11-Oct-2006 03:19
Here is a nifty function to export an object with var_export without the keys, which can be useful if you want to export an array but don't want the keys (for example if you want to be able to easily add something in the middle of the array by hand).

<?
function var_export_nokeys ($obj, $ret=false) {
   
$retval = preg_replace("/'?\w+'?\s+=>\s+/", '', var_export($obj, true));
    if (
$ret===true) {
        return
$retval;
    } else {
        print
$retval;
    }
}
?>

Works the same as var_export obviously. I found it useful, maybe someone else will too!
nobody at nowhere dot de
30-Aug-2006 07:48
Here is a bit code, what will read an saved object and turn it into an array.
Please note: It is very lousy style. Only an an idea.

$data = file_get_contents("test.txt");
$data = preg_replace('/class .*{/im', 'array (', $data);
$data = preg_replace('/\}/im', ')', $data);
$data = preg_replace('/var /im', '', $data);
$data = preg_replace('/;/im', ',', $data);
$data = preg_replace('/=/im', '=>', $data);
$data = preg_replace('/=>>/im', '=>', $data);
$data = preg_replace('/\$(.*?) /im', '"$1"', $data);
eval('$O = ' . $data . ';');
print_r($O);
Zorro
05-Sep-2005 03:24
This function can't export EVERYTHING. Moreover, you can have an error on an simple recursive array:

$test = array();
$test["oops"] = & $test;

echo var_export($test);

=>

Fatal error:  Nesting level too deep - recursive dependency? in ??.php on line 59
linus at flowingcreativity dot net
05-Jul-2005 01:50
<roman at DIESPAM dot feather dot org dot ru>, your function has inefficiencies and problems. I probably speak for everyone when I ask you to test code before you add to the manual.

Since the issue of whitespace only comes up when exporting arrays, you can use the original var_export() for all other variable types. This function does the job, and, from the outside, works the same as var_export().

<?php

function var_export_min($var, $return = false) {
    if (
is_array($var)) {
       
$toImplode = array();
        foreach (
$var as $key => $value) {
           
$toImplode[] = var_export($key, true).'=>'.var_export_min($value, true);
        }
       
$code = 'array('.implode(',', $toImplode).')';
        if (
$return) return $code;
        else echo
$code;
    } else {
        return
var_export($var, $return);
    }
}

?>
roman at DIESPAM dot feather dot org dot ru
19-Mar-2005 06:46
Function that exports variables without adding any junk to the resulting string:
<?php
function encode($var){
    if (
is_array($var)) {
       
$code = 'array(';
        foreach (
$var as $key => $value) {
           
$code .= "'$key'=>".encode($value).',';
        }
       
$code = chop($code, ','); //remove unnecessary coma
       
$code .= ')';
        return
$code;
    } else {
        if (
is_string($var)) {
            return
"'".$var."'";
        } elseif (
is_bool($code)) {
            return (
$code ? 'TRUE' : 'FALSE');
        } else {
            return
'NULL';
        }
    }
}

function
decode($string){
    return eval(
'return '.$string.';');
}
?>
The resulting string can sometimes be smaller, that output of serialize(). May be useful for storing things in the database.
paul at worldwithoutwalls dot co dot uk
25-Nov-2004 04:22
var_export() differs from print_r() for variables that are resources, with print_r() being more useful if you are using the function for debugging purposes.
e.g.
<?php
$res
= mysql_connect($dbhost, $dbuser, $dbpass);
print_r($res); //output: Resource id #14
var_export($res); //output: NULL
?>
aidan at php dot net
11-Jun-2004 01:53
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
php_manual_note at bigredspark dot com
16-Oct-2003 04:43
[john holmes]
True, but that method would require you to open and read the file into a variable and then unserialize it into another variable.

Using a file created with var_export() could simply be include()'d, which will be less code and faster.

[kaja]
If you are trying to find a way to temporarily save variables into some other file, check out serialize() and unserialize() instead - this one is more useful for its readable property, very handy while debugging.

[original post]
If you're like me, you're wondering why a function that outputs "correct PHP syntax" is useful. This function can be useful in implementing a cache system. You can var_export() the array into a variable and write it into a file. Writing a string such as

<?php
$string
= '<?php $array = ' . $data . '; ?>';
?>

where $data is the output of var_export() can create a file that can be easily include()d back into the script to recreate $array.

The raw output of var_export() could also be eval()d to recreate the array.

---John Holmes...

웹 서비스> <var_dump
Last updated: Fri, 24 Jul 2009
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites