note 94333 added to function.var-export
| From: | rarioj at gmail dot com | Date: | Thu, 29 Oct 2009 06:43:49 +0000 |
| Subject: | note 94333 added to function.var-export | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-162228@lists.php.net to get a copy of this message | ||
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)
?>
----
Server IP: 202.158.52.162
Probable Submitter: 125.167.108.115
----
Manual Page -- http://www.php.net/manual/en/function.var-export.php
Edit -- https://master.php.net/note/edit/94333
Del: integrated -- https://master.php.net/note/delete/94333/integrated
Del: useless -- https://master.php.net/note/delete/94333/useless
Del: bad code -- https://master.php.net/note/delete/94333/bad+code
Del: spam -- https://master.php.net/note/delete/94333/spam
Del: non-english -- https://master.php.net/note/delete/94333/non-english
Del: in docs -- https://master.php.net/note/delete/94333/in+docs
Del: other reasons-- https://master.php.net/note/delete/94333
Reject -- https://master.php.net/note/reject/94333
Search -- https://master.php.net/manage/user-notes.php