PHP物件導向中的重要知識點(二)_PHP教程

來源:互聯網
上載者:User
1. __toString: 當對象被列印時,如果該類定義了該方法,則列印該方法的傳回值,否則將按照PHP的預設行為輸出列印結果。該方法類似於Java中的toString()。 複製代碼privateField = "This is a private Field.\n"; $this->publicField = "This is a public Field.\n"; } public function __get($property) { print "__get() is called.\n"; $method = "get${property}"; if (method_exists($this, $method)) { return $this->$method(); } return "This is undefined field.\n"; } public function getPrivateField() { return $this->privateField; }} $testObj = new TestClass();print $testObj->privateField;print $testObj->undefinedField;print $testObj->publicField;複製代碼 運行結果如下: Stephens-Air:Desktop$ php Test.php __get() is called.This is a private Field.__get() is called.This is undefined field.This is a public Field. __set()方法被調用的規則和__get()基本相同,差別是用於攔截未定義或不可見類屬性的賦值操作。另外,該方法接收兩個參數,分別是屬性名稱和要設定的值。見如下程式碼範例: 複製代碼privateField = "This is a private Field.\n"; $this->publicField = "This is a public Field.\n"; } public function __get($property) { print "__get() is called.\n"; $method = "get${property}"; if (method_exists($this, $method)) { return $this->$method(); } return "This is an undefined field.\n"; } public function __set($property, $value) { print "__set is called.\n"; $method = "set${property}"; if (method_exists($this, $method)) { $this->$method($value); } else { print "This is an undefined field.\n"; } } public function getPrivateField() { return $this->privateField; } public function setPrivateField($value) { $this->privateField = $value; }} $testObj = new TestClass();$testObj->privateField = "This is a private Field after set.\n";$testObj->undefinedField = "This is a undefined Field after set.\n";$testObj->publicField = "This is a public Field after set.\n"; print $testObj->privateField;print $testObj->undefinedField;print $testObj->publicField;複製代碼 運行結果如下: 複製代碼Stephens-Air:Desktop$ php Test.php __set is called.__set is called.This is an undefined field.__get() is called.This is a private Field after set.__get() is called.This is an undefined field.This is a public Field after set.複製代碼3. __isset和__unset: 這兩個攔截方法被調用的規則和__get()和__set()非常類似,只是用於類中不存在或不可見屬性被isset()和unset()兩個全域方法應用時才會被分別觸發。 複製代碼privateField = "Defined private field"; $this->publicField = "Defined public field"; } public function __isset($property) { print "__isset is called.\n"; return isset($this->$property); } public function __unset($property) { print "__unset is called.\n"; if (isset($this->$property)) { unset($this->$property); } }} $testObj = new TestClass();print 'isset($testObj->privateField) is '.(isset($testObj->privateField) ? "true" : "false")."\n";print 'isset($testObj->undefinedField) is '.(isset($testObj->undefinedField) ? "true" : "false")."\n";print 'isset($testObj->publicField) is '.(isset($testObj->publicField) ? "true" : "false")."\n"; print "After unset......\n";//下面兩個函數調用後,$testObj的兩個對象屬性均會變為不可用。//另外從輸出結果來看,__unset方法僅僅被調用一次,因為publicField為可見屬性,所以__unset不會因該屬性而被調用。unset($testObj->privateField);unset($testObj->publicField); print 'isset($testObj->privateField) is '.(isset($testObj->privateField) ? "true" : "false")."\n";print 'isset($testObj->publicField) is '.(isset($testObj->publicField) ? "true" : "false")."\n";複製代碼 運行結果如下: 複製代碼Stephens-Air:Desktop$ php Test.php __isset is called.isset($testObj->privateField) is true__isset is called.isset($testObj->undefinedField) is falseisset($testObj->publicField) is trueAfter unset......__unset is called.__isset is called.isset($testObj->privateField) is false__isset is called.isset($testObj->publicField) is false複製代碼4. __call: __call()方法是一個非常有用但又非常容易被濫用的攔截方法。當對象使用者試圖訪問當前對象未定義的成員函數時,__call()會被自動調用,同時傳遞兩個參數,分別為函數名稱和傳遞給調用函數的所有參數(數組)。__call方法返回的任何值都會返回給函數調用者,就如同該成員函數真實存在一樣。下面給出一個非常有用的委託樣本。 複製代碼delegateObj = new DelegateClass(); } public function __call($method, $args) { $this->delegateObj->$method($args[0],$args[1]); }} $testObj = new TestClass();$testObj->printMessage("hello","world");複製代碼 運行結果如下: Stephens-Air:Desktop$ php Test.php DelegateClass:delegatedMethod is called.$arg1 = helloand $arg2 = world 從以上樣本可以看出,TestClass並未聲明printMessage成員方法,但是通過__call()方法的巧妙橋接直接傳遞給了委派物件。個人認為該技巧為雙刃劍,切勿過度使用。 5. 回呼函數: 回呼函數的應用情境無須多述,在C/C++中充斥著無數的回呼函數典型用例。 這裡只是簡單給出PHP中回呼函數的使用規則。見如下範例程式碼和關鍵性注釋: 複製代碼name = $name; $this->price = $price; }} class ProcessSale { private $callbacks; function registerCallback($cb) { if (!is_callable($cb)) { throw new Exception("callback not callable."); } $this->callbacks[] = $cb; } function sale($product) { print "{$product->name}: processing \n"; foreach ($this->callbacks as $cb) { //以下兩種調用方式均可。 call_user_func($cb, $product); $cb($product); } }} $logger = function($product) { print " logging ({$product->name})\n";}; $processor = new ProcessSale();$processor->registerCallback($logger);$processor->sale(new Product("shoes",6));print "\n";$processor->sale(new Product("coffee",6));複製代碼 運行結果如下: 複製代碼Stephens-Air:Desktop$ php Test.php shoes: processing logging (shoes) logging (shoes) coffee: processing logging (coffee) logging (coffee)複製代碼6. use(閉包): 在Javascript中存在大量的閉包應用,PHP中的閉包則是通過use關鍵字來完成的。對於閉包這個概念本身而言,簡要的說就是函數內的代碼可以訪問其父範圍中的變數。見如下範例程式碼和關鍵性注釋: 複製代碼name = $name; $this->price = $price; }} class ProcessSale { private $callbacks; function registerCallback($cb) { if (!is_callable($cb)) { throw new Exception("callback not callable."); } $this->callbacks[] = $cb; } function sale($product) { print "{$product->name}: processing \n"; foreach ($this->callbacks as $cb) { $cb($product); } }} class Totalizer { static function warnAmount($amt) { $count = 0; //注意這裡的$amt和$count均為閉包變數,其中&$count是以引用的形式傳遞的,即一旦函數內部修改了該變數的值, //那麼下次再訪問該閉包變數時,$count將為之前調用中修改後的值。 return function($product) use($amt, &$count) { $count += $product->price; print " count: $count\n"; if ($count > $amt) { print " high price reached: {$count}\n"; } }; }} $processor = new ProcessSale();$processor->registerCallback(Totalizer::warnAmount(8));$processor->sale(new Product("shoes",6));$processor->sale(new Product("coffee",6));複製代碼 運行結果如下: shoes: processing count: 6coffee: processing count: 12 high price reached: 12註:該Blog中記錄的知識點,是在我學習PHP的過程中,遇到的一些PHP和其他物件導向語言相比比較獨特的地方,或者是對我本人而言確實需要簿記下來以備後查的知識點。雖然談不上什麼深度,但是還是希望能與大家分享。

http://www.bkjia.com/PHPjc/635016.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/635016.htmlTechArticle1. __toString: 當對象被列印時,如果該類定義了該方法,則列印該方法的傳回值,否則將按照PHP的預設行為輸出列印結果。該方法類似於Java中...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.