PHP如何像javabean一样get+字段名方式取值

之前学java的时候,java有个javabean直接get或set方式获取和设置属性的直,但需要先定义好需要的属性

现在php把从数据库中查出直,然后get+字段名次返回该字段的直,set+字段名称设置新的直

如name属性获取getName();

定义函数:使用php魔术方法__call函数

public function __call($method,$args){
  $key = strtolower(preg_replace('/(.)([A-Z])/', "$1_$2", $method));
  switch (substr($method, 0, 3)) {
            case 'get' :
                $data = $this->getData($key, isset($args[0]) ? $args[0] : null);
                return $data;
            case 'set' :
                $result = $this->setData($key, isset($args[0]) ? $args[0] : null);
                return $result;

            case 'uns' :
                $result = $this->unsetData($key);
                return $result;

            case 'has' :
                return isset($this->_data[$key]);
        }
}

  

 

posted @ 2017-03-12 18:24  蚂蚁小圆  阅读(511)  评论(0编辑  收藏  举报