php 中的魔术方法:
<?php class cat{ public function __get($property) { return $this->{$property}; } public function __call($parm1,$parm2) { print_r($parm1); print_r($parm2); } public function __set($var,$val) { echo $var."|".$val." "; $this->$var = $val; } public function __clone() { echo "clone func invoke"." "; } public function __isset($var) { echo "via __isset view isset".$var; } public function __unset($var) { echo "via __unset unset".$var; } public static function __callStatic($parm1,$parm2) { echo "__callStatic ".$parm1.var_dump($parm2); } public function __construct() { echo '__construct'; } public function __destruct() { echo '__destruct'; } public function __toString() { return 'cat to string'; } public function __invoke($xxx) { var_dump($xxx); } } $Cat = new cat(); //echo $Cat->name; //$Cat->hello($array=array('a','b')); $Cat->a = 3; $Cat2 = clone $Cat; $Cat2->a = 10; echo $Cat->a; echo $Cat2->a; var_dump(isset($Cat->b)); unset($Cat->b); Cat::ddd('abc'); echo $Cat2; $Cat('abccd'); var_dump(is_callable($Cat));
此外还有:
<?php //student.class.php class Student{ private $full_name = ''; private $score = 0; private $grades = array(); public function __construct($full_name, $score, $grades) { $this->full_name = $full_name; $this->grades = $grades; $this->score = $score; } public function show() { echo $this->full_name; } function __sleep() { echo 'Going to sleep...'; return array('full_name', 'grades', 'score'); } function __wakeup() { echo 'Waking up...'; } } ?> <?php //a.php $student = new Student('bla bla', 'a', array('a' => 90, 'b' => 100)); $student->show(); echo "<br /> "; $s = serialize($student); echo $s ."<br /> "; $fp = fopen('./session.s', 'w'); fwrite($fp, $s); fclose($fp); ?> <?php //b.php $s = implode('', file("./session.s")); echo $s ."<br /> "; $a = unserialize($s); $a->show(); ?>
其中__invoke是5.3以后加入的。