php5 學習記錄(2)
一、重載效能
1、屬性和方法的重載
php 允許通過實現特殊的代理方法對屬性的訪問和方法的調用進行重載,這些代理方法將在相關的屬性或者方法不存在時調用。這種特性讓你在中端這些動作並定義你自己的功能時獲得巨大的靈活性。
你可以實現下面的方法原型:
function __get($property)// 傳遞屬性的名字,並且返回屬性值
function __set($property, $value)// 傳遞屬性的名字和新的值
function __call($method, $args)// 傳遞方法的名字和一個數字索引的數組,數字包含傳遞的參數,第一個參數的索引是0。
?
?
class Users { private $arr = array(); function __get($name) { return $this->arr[$name] === NULL ? 'null' : $this->arr[$name]; } function __set($name, $value) { $this->arr[$name] = $value; }}$user = new Users();$user->a = 'xiezheng';print $user->a;
__call()具有很多用途,它主要用來監控一個對象中的其他方法。如果你試著調用一個對象中不存在的方法,__call方法將會被自動調用。
?
class HelloWorld { function display($count) { for($i=0; $i<$count; $i++) print __CLASS__.'
'; return $count; }}class HelloWorldCall { private $obj; function __construct() { $this->obj = new HelloWorld(); } function __call($method, $args) { return call_user_func_array(array($this->obj, $method), $args); }}$hwc = new HelloWorldCall();print $hwc->display(3);?
?
2、使用數組語句訪問的重載。
為了讓你的類能夠重載數組語句的訪問,你的類需要實現ArrayAccess介面。
bool offsetExists($index)
mined offsetGet($index)
void offsetSet($index, $new_value)
void offsetUnset($index)
以上是ArrayAccess需要實現的方法。
?
?
class Users implements ArrayAccess { private $uname; function offsetExists($name) { return $this->uname === NULL; } function offsetGet($name) { return $this->offsetExists($this->uname) ? 'NULL' : $this->uname; } function offsetSet($name, $value) { $this->uname = $value; } function offsetUnset($name) { $this->uname = null; }}$user = new Users();$user['name'] = 'xiezheng';// unset($user['name']);print $user['name'];?
?
?