首页 > 编程 > PHP > 正文

使用PHP魔术方法实现重载

2019-11-10 19:23:37
字体:
来源:转载
供稿:网友

之前对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方法的方式来操作对象的字段值。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表