码迷,mamicode.com
首页 > 编程语言 > 详细

php 以数组形式访问对象

时间:2018-05-26 15:33:16      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:any   orm   offset   boolean   justify   hit   com   msu   abs   

官方文档上:

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

 

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

php 以数组形式访问对象

标签:any   orm   offset   boolean   justify   hit   com   msu   abs   

原文地址:https://www.cnblogs.com/burningc/p/9092829.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!