PHP

PHP: 如何像关联数组那样访问对象的属性 - PHP技巧与解决方案

silverwq
2022-05-31 / 0 评论 / 234 阅读 / 正在检测是否收录...

一、概述

一般我们访问关联数组,都是形如$arr['key']形式访问值,我们希望也能这样数组式访问对象的属性。

二、实现


class obj implements arrayaccess
{
    private $container = [
        "one" => 1,
        "two" => 2,
        "three" => 3,
    ];

    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            //$obj[] = 'Append 1';
            $this->container[] = $value;
        } else {
            // $obj["two"] = "A value";
            $this->container[$offset] = $value;
        }
    }

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

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

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

$obj = new Obj();
$obj['one'];//1
$obj['two'];//2
$obj['three'];//3
0

评论 (0)

取消