zoukankan      html  css  js  c++  java
  • php 以数组形式访问对象

    官方文档上:

    ArrayAccess {
    /* Methods */
    abstract public boolean offsetExists ( mixed $offset )
    abstract public mixed offsetGet ( mixed $offset )
    abstract public void offsetSet ( mixed $offset , mixed $value )
    abstract public void offsetUnset ( mixed $offset )
    }
    

      

    实现上面的方法,下面举个实例

    <?php
    /**
     * Created by PhpStorm.
     * User: wangHan
     * Date: 2016/10/21
     * Time: 14:07
     */
    class Human implements ArrayAccess
    {
        private $elements;
    
        public function __construct()
        {
            $this->elements = [
                "boy" => "male",
                "girl" => "female"
            ];
        }
    
        public function offsetExists($offset)
        {
            // TODO: Implement offsetExists() method.
            return isset($this->elements[$offset]);
        }
    
        public function offsetGet($offset)
        {
            // TODO: Implement offsetGet() method.
            return $this->elements[$offset];
        }
    
        public function offsetSet($offset, $value)
        {
            // TODO: Implement offsetSet() method.
            $this->elements[$offset] = $value;
        }
    
        public function offsetUnset($offset)
        {
            // TODO: Implement offsetUnset() method.
            unset($this->elements[$offset]);
        }
    }
    
    $human = new Human();
    $human['people'] = "boyAndGirl"; ////自动调用offsetSet
    if(isset($human['people'])) {   ////自动调用offsetExists
        echo $human['boy'];//自动调用offsetGet
        echo '<br />';
        unset($human['boy']);//自动调用offsetUnset
        var_dump($human['boy']);
    }
    // // 输出结果  male   null

     

  • 相关阅读:
    Java小程序1(2015-8-6)
    Java小程序(2015-8-6)
    Java基础2(2015-8-3)变量与数据类型
    Java小程序2(2015-8-2)
    Java小程序1(2015-8-2)
    MySql修改时区
    6、ssm整合(干货)
    关于 TreeMap 和 HashMap 的去重操作
    5、SpringMVC:JSON
    4、配置MVC的乱码过滤:解决中文乱码
  • 原文地址:https://www.cnblogs.com/burningc/p/9092829.html
Copyright © 2011-2022 走看看