php5 學習記要(2)

來源:互聯網
上載者:User
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'];
?

?

?

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.