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)
}

一个不可多得的例子,欢迎讨论
...全文
168 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
yrs 2001-07-26
  • 打赏
  • 举报
回复
阅 :)
孟子E章 2001-07-25
  • 打赏
  • 举报
回复

谢谢你的例子!;)

21,893

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧