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)
}
一个不可多得的例子,欢迎讨论