__sleep() 和 __wakeup()
public
array
__sleep (
void )
void
__wakeup (
void )
class User {
public $name;
public $id;
function __construct() {
$this->id = uniqid();//give user a unique ID 赋予一个不同的ID
}
function __sleep() {
return(array("name"));//do not serialize this->id 不串行化id
}
function __wakeup() {
$this->id = uniqid();//give user a unique ID 不重新赋值的话unserialize后id为null
}
}
$u = new User;
$u->name = "HAHA";
$s = serialize($u);//serialize it 串行化 注意不串行化id属性,id的值被抛弃
$u2 = unserialize($s);//unserialize it 反串行化 id被重新赋值
//$u and $u2 have different IDs $u和$u2有不同的ID
var_dump($u);
var_dump($u2);
输出结果:
object(User)[1] public 'name' => string 'HAHA' (length=4) public 'id' => string '501b79c3f1077' (length=13)
object(User)[2] public 'name' => string 'HAHA' (length=4) public 'id' => string '501b79c3f10a6' (length=13)
__invoke()
当尝试以调用函数的方式调用一个对象时, __invoke() 方法会被自动调用。class CallableClass {
function __invoke($x) {
var_dump($x);
}
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
__set_state()
static
object
__set_state (
array
$properties
)
当调用var_export()时,这个静态 方法会被调用(自PHP 5.1.0起有效)。
本方法的唯一参数是一个数组,其中包含按array('property' => value, ...)格式排列的类属性。
class A {
public $var1;
public $var2;
public static function __set_state($an_array) {// As of PHP 5.1.0
$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);