使用PHP魔术方法实现重载
来源:互联网 发布:平板电脑拍照软件 编辑:程序博客网 时间:2024/06/15 12:50
之前对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方法的方式来操作对象的字段值。
0 0
- 使用PHP魔术方法实现重载
- PHP属性重载,魔术方法
- php通过魔术方法__call实现类函数重载
- php中使用魔术方法实现aop
- PHP魔术方法之__call重载方法
- PHP魔术方法使用总结
- PHP魔术方法的使用
- PHP魔术方法使用总结
- php魔术变量-重载
- 魔术方法之重载
- PHP中的魔术方法和魔术常量简介和使用
- PHP魔术方法和魔术常量介绍及使用
- PHP魔术方法和魔术常量介绍及使用
- PHP魔术方法和魔术常量介绍及使用
- php中的类与对象(魔术方法、克隆和重载)
- PHP利用魔术方法实现准AOP
- php魔术常量,魔术方法
- php魔术方法的使用(总结)
- excel中输入随机数字和从引用其他表格数据
- [LeetCode]124. Binary Tree Maximum Path Sum
- var、let、const小解
- 在JAVA中如何获取当前日期
- shiro 自定义认证filter
- 使用PHP魔术方法实现重载
- 禁用鼠标右键,选中
- Struts2一览
- GridViewAdapter
- spring和resteasy集成,构建restful风格服务
- JSP退出和注销整个页面
- Other_3.仿-慕课网课程选项卡_效果1(上下伸缩)
- unity 从相机的位置发射小球并打到鼠标点击的位置
- MYSQL 客户端与服务器关系