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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM