日期:2014-05-16 浏览次数:20465 次
class People { protected $_alive; public function __construct() { $this->_alive = true; echo 'Birth'.PHP_EOL; } public function __destruct() { $this->_alive = false; echo 'Die'.PHP_EOL; } } //主动销毁对象 $test = new Test(); unset($test); sleep(1); //程序完成后自动销毁对象 $test = new Test(); sleep(1);
//例如:我们可以构建一个不确定属性的数据记录类 class Record { protected $_data; public function __get($name) { if (isset($this->_data[$name])) { return $this->_data; } return false; } public function __set($name, $value) { $this->_data = $value; } } $record = new Record(); $record->name = 'andrew'; echo 'My name is '.$record->name.PHP_EOL;
//例如: class People { public $name; public $sex; private $_age; public function __construct($name, $sex, $age) { $this->name = $name; $this->sex = $sex; $this->_age = $age; } public function __isset($name) { echo 'The property '.$name.' not exists'.PHP_EOL; } public function __unset($name) { echo 'The property '.$name.' can not be unset'.PHP_EOL; } } $people = new People('andrew', 'male', 28); isset($people->name); isset($people->real_name); unset($people->_age);
//例如:我们假定人只有跳走两种行为 class People { public function jump() { echo 'I can jump'.PHP_EOL; } public function walk() { echo 'I can walk'.PHP_EOL; } public function __call($method, $args) { echo 'I can not '.$method.PHP_EOL; } //此方法必须是静态方法,且在php5.3版本下可用 public static function __callStatic($method, $args) { echo 'We can not'.$method.PHP_EOL; } } $people = new People(); $people->jump(); $people->walk(); $people->fly(); People::fly();