<?php
namespace org\Util;
/**
* 获取器
*
*/
class Acquire{
public $data;
private $type;
/**
* 获取器 获取数据对象的值
* @access public
* @param string $name 名称
* @return mixed
*/
public function __get($name) {
$value = isset($this->data[$name]) ? $this->data[$name] : null;
// 检测属性获取器
$method = 'get' . \think\Loader::parseName($name, 1) . 'Attr';
if (method_exists($this, $method)) {
return $this->$method($value, $this->data);
} elseif (!is_null($value) && isset($this->type[$name])) {
// 类型转换
$type = $this->type[$name];
if (strpos($type, ':')) {
list($type, $param) = explode(':', $type, 2);
}
switch ($type) {
case 'integer':
$value = (int) $value;
break;
case 'float':
if (empty($param)) {
$value = (float) $value;
} else {
$value = (float) number_format($value, $param);
}
break;
case 'boolean':
$value = (bool) $value;
break;
case 'datetime':
$format = !empty($param) ? $param : $this->dateFormat;
$value = date($format, $value);
break;
case 'json':
case 'array':
$value = json_decode($value, true);
break;
case 'object':
$value = json_decode($value);
break;
}
} elseif (is_null($value) && method_exists($this, $name)) {
// 获取关联数据
$value = $this->relation->getRelation($name);
// 保存关联对象值
$this->data[$name] = $value;
}
return $value;
}
public function __construct($data) {
foreach ($data as $k=>$v){
if(is_array($v)){
$name=get_class($this);
$data[$k]=new $name($v);
}
}
$this->data=$data;
}
//__set()方法用来设置私有属性
function __set($n, $v) {
$this->$n = $v;
}
}先一定一个获取器继承上面的类然后实例化这个获取器传入要使用获取器的数据
$data->attr;
这就使用了获取器了
支持多维数组 一维数组跟多维数组使用的方式略有区别哦 看代码就能看出来 使用后有不懂的 回帖
最佳答案