(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
var_export — 输出或返回一个变量的字符串表示
var_export() 函数返回关于传递给该函数的变量的结构信息,它和 var_dump() 函数类似,不同的是其返回的表示是合法的 PHP 代码。
expression
想要输出的变量名。
return
此参数为 true
时,var_export() 将返回一个变量,而不是输出它。
参数 return
为 true
时返回变量,否则返回 null
。
注意:
当使用了
return
参数时,本函数使用其内部输出缓冲,因此不能在 ob_start() 回调函数的内部使用。
版本 | 说明 |
---|---|
7.3.0 |
Now exports stdClass objects as an array cast to
an object ((object) array( ... ) ), rather than using the
nonexistent method stdClass::__setState().
The practical effect is that now stdClass is
exportable, and the resulting code will even work on earlier versions of
PHP.
|
示例 #1 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
示例 #2 输出类 stdClass (自 PHP 7.3.0 起)
<?php
$person = new stdClass;
$person->name = 'ElePHPant ElePHPantsdotter';
$person->website = 'https://php.net/elephpant.php';
var_export($person);
以上例程会输出:
(object) array( 'name' => 'ElePHPant ElePHPantsdotter', 'website' => 'https://php.net/elephpant.php', )
示例 #3 输出对象 (自 PHP 5.1.0 起)
<?php
class A { public $var; }
$a = new A;
$a->var = 5;
var_export($a);
?>
以上例程会输出:
A::__set_state(array( 'var' => 5, ))
示例 #4 使用 __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" }
注意:
类型为 resource 的变量无法通过此函数输出。
注意:
var_export() does not handle circular references as it would be close to impossible to generate parsable PHP code for that. If you want to do something with the full representation of an array or object, use serialize().
When var_export() exports objects, the leading backslash is not included in the class name of namespaced classes for maximum compatibility.
注意:
To be able to evaluate the PHP generated by var_export(), all processed objects must implement the magic __set_state method. The only exception is stdClass, which is exported using an array cast to an object.