php的class中的两个特殊方法(method)

yorgo 2001-07-25 03:10:52
Serializing an object is just like serializing an array, but there are a couple of extra cool features for an object. The __sleep() and __wakeup() methods are illustrated here:

<?
class test {
function test($filename=NULL,$mode=NULL) {
echo "constructor called\n";
$this->filename = $filename;
$this->mode = $mode;

// we could call $this->__wakeup() instead
if ($this->filename && $this->mode) {
$this->fd = fopen($this->filename,$this->mode);
}

}

function __sleep() {
echo "sleep\n";
// return list of instance-variables to be serialized
return array("filename","mode");
}

function __wakeup() {
echo "wakeup\n";
// all serialized instance variables are set now, inititalize
// the non-serializeable ones
if ($this->filename && $this->mode) {
$this->fd = fopen($this->filename,$this->mode);
}
}

function __string_value() {
return "hallo i'm using $this->filename\n";
}
}

$a = new test("serialize2.php","r");
var_dump($a);
$b = serialize($a);
var_dump($b);
$a = unserialize($b);
var_dump($a);
?>


Output:
constructor called
object(test)(3) {
["filename"]=>
string(14) "serialize2.php"
["mode"]=>
string(1) "r"
["fd"]=>
resource(1) of type (file)
}
sleep
string(71) "O:4:"test":2:{s:8:"filename";s:14:"serialize2.php";s:4:"mode";s:1:"r";}"
wakeup
object(test)(3) {
["filename"]=>
string(14) "serialize2.php"
["mode"]=>
string(1) "r"
["fd"]=>
resource(2) of type (file)
}

一个不可多得的例子,欢迎讨论
...全文
97 2 打赏 收藏 举报
写回复
2 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
yrs 2001-07-26
阅 :)
  • 打赏
  • 举报
回复
孟子E章 2001-07-25

谢谢你的例子!;)
  • 打赏
  • 举报
回复
发帖
基础编程

2.1w+

社区成员

从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
帖子事件
创建了帖子
2001-07-25 03:10
社区公告
暂无公告