Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
PHP: var_export - Manual
[go: Go Back, main page]

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

search for in the

Verisign Payflow Pro 関数" width="11" height="7"/> <var_dump
Last updated: Thu, 03 May 2007

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() は変数表現を出力する代わりに返します。

注意: この関数は、 このパラメータに対して内部的に出力バッファリングを使用しています。 そのため、ob_start() コールバック関数の中で使用することはできません。

返り値

return パラメータが使用され TRUE と評価される場合、 変数表現を返します。そうでない場合、この関数は NULL を返します。

変更履歴

バージョン説明
5.1.0 マジックメソッド __set_state を使用することで、 クラスを含む配列やクラスをエクスポートできるようになりました。

例 2494. var_export() の例

<?php
$a
= array (1, 2, 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($b, true);
echo
$v;

?>

上の例の出力は以下となります。


3.1

    

例 2495. PHP 5.1.0 以降でのクラスのエクスポート

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

上の例の出力は以下となります。


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

    

例 2496. __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($a, true) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);
?>

上の例の出力は以下となります。


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

    

注意

注意: リソース型 の変数は、 この関数ではエクスポートする事ができません。

注意: var_export() では循環参照を扱うことができません。 循環参照を表す解析可能な PHP コードを生成することは、不可能に近いからです。 配列やオブジェクトを完全な形式で扱いたい場合は serialize() を使用してください。

参考

print_r()
serialize()
var_dump()



add a note add a note User Contributed Notes
var_export
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...

 
show source | credits | sitemap | contact | advertising | mirror sites