ArrayAccess(数组式访问)接口

匿名 (未验证) 提交于 2019-12-02 23:05:13

Yii、laravel源代码中,注意到有对象以数组的形式访问数据,即下面原理

<?php 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); ?>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!