PHP重載
PHP中的重載指的是動態(tài)的創(chuàng)建屬性與方法,是通過魔術(shù)方法來實現(xiàn)的。屬性的重載通過__set,__get,__isset,__unset來分別實現(xiàn)對不存在屬性的賦值、讀取、判斷屬性是否設(shè)置、銷毀屬性。
<strong style="background-color:rgb(255,255,255)">class Car { private $ary = array(); public function __set($key, $val) { $this->ary[$key] = $val; } public function __get($key) { if (isset($this->ary[$key])) { return $this->ary[$key]; } return null; } public function __isset($key) { if (isset($this->ary[$key])) { return true; } return false; } public function __unset($key) { unset($this->ary[$key]); }}$car = new Car();$car->name = '汽車'; //name屬性動態(tài)創(chuàng)建并賦值echo $car->name;</strong>
方法的重載通過__call來實現(xiàn),當調(diào)用不存在的方法的時候,將會轉(zhuǎn)為參數(shù)調(diào)用__call方法,當調(diào)用不存在的靜態(tài)方法時會使用__callStatic重載。
<strong style="background-color:rgb(255,255,255)">class Car { public $speed = 0; public function __call($name, $args) { if ($name == 'speedUp') { $this->speed += 10; } }}$car = new Car();$car->speedUp(); //調(diào)用不存在的方法會使用重載echo $car->speed;</strong>
版權(quán)聲明:本文為博主原創(chuàng)文章,未經(jīng)博主允許不得轉(zhuǎn)載。
PHP怎么學習?PHP怎么入門?PHP在哪學?PHP怎么學才快?不用擔心,這里為大家提供了PHP速學教程(入門到精通),有需要的小伙伴保存下載就能學習啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://www.miracleart.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號