1. 程式人生 > >PHP中的ArrayAccess用法

PHP中的ArrayAccess用法

最近看laravel原始碼,發現裡面用了很多框架類實現了ArrayAccess介面,以前對這塊不是很熟悉,查了一下這個語法的用法,發現這個其實就是實現讓物件以陣列形式來使用。

在官方文件上:

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
//Configuration Class
class Configuration implements ArrayAccess { 

    static private $config;
    private $configarray;

    private function __construct() {
        $this->configarray = array(
            "Wang" => "Male",
            "Han" => "Female"
        );
    }

    public static function instance() {
        if (self::$config == null) {
            self::$config = new Configuration();
        }
        return self::$config;
    }

    function offsetExists($index) {
        return isset($this->configarray[$index]);
    } 

    function offsetGet($index) {
        return $this->configarray[$index];
    } 

    function offsetSet($index, $newvalue) {
        $this->configarray[$index] = $newvalue;
    } 

    function offsetUnset($index) {
        unset($this->configarray[$index]);
    }
} 

$config = Configuration::instance();
print $config["Wang"];
//正如你所預料的,程式的輸出是"Male"。
//假如我們做下面那樣的動作:
$config = Configuration::instance();
print $config["Han"];
$config['Han'] = "Wang's Lover";
// config 
$configTest = Configuration::instance();
print $configTest ['Han']; //是的,也正如預料的,輸出的將是Wang's Lover