Voting

: two minus one?
(Example: nine)

The Note You're Voting On

rarioj at gmail dot com
15 years ago
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)

?>

<< Back to user notes page

To Top