PHP用数组方式访问对象

在平时开发中,经常会遇到一个对象被转换成数组后,经过复杂的业务逻辑处理后,数组又被传递给需要接收对象的方法使用,此时代码就会报 Trying to get property 'name' of non-object 错误,其实在PHP5版本时,官方就引入了一个 ArrayAccess 的接口,可以实现用数组方式访问对象,只要实现了该接口的几个方法,就可以让数据对象用数组语法使用。

接口摘要

interface ArrayAccess {
    // 判断一个下标是否存在
    public offsetExists(mixed $offset): bool
    // 通过数组下标获取值
    public offsetGet(mixed $offset): mixed
    // 设置数组下标对应的值
    public offsetSet(mixed $offset, mixed $value): void
    // 根据下标删除一个值
    public offsetUnset(mixed $offset): void
}

官方示例

class Obj implements ArrayAccess {
    private $container = array();

    public function __construct() {
        $this->container = array(
            "one"   => 1,
            "two"   => 2,
            "three" => 3,
        );
    }

    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetExists($offset) {
        return isset($this->container[$offset]);
    }

    public function offsetUnset($offset) {
        unset($this->container[$offset]);
    }

    public function offsetGet($offset) {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}

$obj = new Obj;

var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);
$obj[] = 'Append 1';
$obj[] = 'Append 2';
$obj[] = 'Append 3';
print_r($obj);

以上例程的输出如下:

bool(true)
int(2)
bool(false)
string(7) "A value"
obj Object
(
    [container:obj:private] => Array
        (
            [one] => 1
            [three] => 3
            [two] => A value
            [0] => Append 1
            [1] => Append 2
            [2] => Append 3
        )
)

从以上例子可以看出,对象已经支持用数组语法获取和设置属性值,当我们从数据库查询出数据后,可以将其封装成数据对象,方便扩展数据处理方法,同时也保证了,在后期数据传递过程中,无需转成真正的数组也能按数组语法使用,目前比较流行的 laravel 框架的 Eloquent 集合 就是用此方法实现的。

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章