以数组的方式访问对象内容

对象也能当作数组


在观看Symfony源码的时候,发现了这种写法$this['logger'] = $value   $this  是个对象。纳尼,对象也能这么玩,然后我赶紧就试了一下,然后,显而易见,挂掉了。原来,之所以能够当作数组来用是因为,实现了PHP的一个叫做ArrayAccess 接口,随手写了一个示例。
接口说明::提供像访问数组一样访问对象的能力的接口。

<?php
class base implements ArrayAccess {
    protected $values;
    protected $keys;

    /**
     * Whether a offset exists
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
     * @param mixed $offset <p>
     * An offset to check for.
     * </p>
     * @return boolean true on success or false on failure.
     * </p>
     * <p>
     * The return value will be casted to boolean if non-boolean was returned.
     * @since 5.0.0
     */
    public function offsetExists($offset){
        return isset($this->keys[$offset]);
    }

    /**
     * Offset to retrieve
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
     * @param mixed $offset <p>
     * The offset to retrieve.
     * </p>
     * @return mixed Can return all value types.
     * @since 5.0.0
     */
    public function offsetGet($offset){
        return $this->values[$offset];
    }

    /**
     * Offset to set
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
     * @param mixed $offset <p>
     * The offset to assign the value to.
     * </p>
     * @param mixed $value <p>
     * The value to set.
     * </p>
     * @return void
     * @since 5.0.0
     */
    public function offsetSet($offset, $value){
        $this->values[$offset] = $value;
    }

    /**
     * Offset to unset
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
     * @param mixed $offset <p>
     * The offset to unset.
     * </p>
     * @return void
     * @since 5.0.0
     */
    public function offsetUnset($offset){
        unset($this->values[$offset]);
    }
}

class im extends base{
    public function addAttr($key, $value){
        $this[$key] = $value;
        $this->keys[] =$key;
    }

    public function showAttr(){
        return array_combine($this->keys, $this->values);
    }
}
echo '
<pre>';
$im = new im();

$im->addAttr('name', 'zhangsan');
$im->addAttr('addr', 'Shanghai');
$res = $im->showAttr();
echo $im['name'];
var_dump($im);
posted @ 2020-04-10 14:11  winlans  阅读(201)  评论(0)    收藏  举报