国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > PHP > 正文

使用PHP魔術方法實現重載

2019-11-10 18:29:52
字體:
來源:轉載
供稿:網友

之前對php中的魔術方法一直有了解,但是對于具體的使用場景則是模模糊糊的。今天了解到了一種使用魔術方法的場景,整理了一下寫出來。

假如一個類中具有較多的變量,對于每一個變量編寫set/get方法是一件非常繁瑣的事情,尤其對于數據庫的查詢結果,有時候字段可以很多。但是直接讓程序調用類中的字段又不被推薦,這時候可以通過對__get、__set和__call方法的使用來解決這個問題。

<?phpclass Basic { PRotected $_properties; /** * Basic constructor. * @param $val */ public function __construct ($val = array()) { $this->_properties = $val; } /** * @param $key * @param $val */ public function __set ($key, $val) { $this->_properties[$key] = $val; } /** * @param $key * @return */ public function __get ($key) { return isset($this->_properties[$key]) ? $this->_properties[$key] : null; } /** * @param $_method * @param $args * @return */ public function __call ($_method, $args) { if(method_exists($this, $_method)) { return $this->$_method($args); } if(substr($_method, 0, 3) == 'get') { return $this->_get($_method); } if(substr($_method, 0, 3) == 'set') { $this->_set($_method, $args); } return null; } /** * @param $_method * @return */ private function _get ($_method) { $_method = substr($_method, 3, strlen($_method)); $key = implode('_', preg_split('#(?=[A-Z])#', lcfirst($_method))); $key = strtolower($key); return isset($this->_properties[$key]) ? $this->_properties[$key] : null; } /** * @param $_method * @param null $args */ private function _set ($_method, $args = null) { $_method = substr($_method, 3, strlen($_method)); $key = implode('_', preg_split('#(?=[A-Z])#', lcfirst($_method))); $key = strtolower($key); $this->_properties[$key] = $args[0]; }}$student = array( 'name' => '張三', 'age' => 18, 'sex' => 'male', 'score' => 99);$basic = new Basic($student);$basic->level = 'A';var_dump($basic->name);//string(6) "張三"var_dump($basic->getLevel());//string(1) "A"$basic->setLevel('B');var_dump($basic->level);//string(1) "B"通過代碼中的方式,相當于對于每個字段默認實現了get/set方法,在對象中可以直接通過getKeyName和setKeyName方法的方式來操作對象的字段值。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 崇义县| 临泉县| 田阳县| 武鸣县| 宕昌县| 长乐市| 阿尔山市| 麻阳| 巨野县| 衡水市| 香格里拉县| 黔南| 云阳县| 漳浦县| 苍溪县| 溆浦县| 井冈山市| 乃东县| 章丘市| 都安| 黄石市| 黄浦区| 宽甸| 新津县| 丹江口市| 阜新市| 平利县| 白河县| 吐鲁番市| 贵溪市| 蒙山县| 织金县| 壤塘县| 盐源县| 定结县| 晋中市| 沂南县| 上蔡县| 寻甸| 台安县| 孝昌县|