ArrayAccess接口介绍,ArrayAccess接口介绍
【 tulaoshi.com - PHP 】
在 PHP5 中多了一系列新接口。在 HaoHappy 翻译的系列文章中 你可以了解到他们的应用。同时这些接口和一些实现的 Class 被归为 Standard PHP Library(SPL)。在 PHP5 中加入了很多特性,使类的重载 (Overloading) 得到进一步的加强。ArrayAccess 的作用是使你的 Class 看起来像一个数组 (PHP的数组)。这点和 C# 的 Index 特性很相似。
下面是 ArrayAccess 的定义:
interface ArrayAccess
boolean offsetExists($index)
mixed offsetGet($index)
void offsetSet($index, $newvalue)
void offsetUnset($index)
//Configuration Class class Configuration implements ArrayAccess {    static private $config;    private $configarray;    private function __construct()    {        // init        $this-configarray = array("Binzy"="Male", "Jasmin"="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["Binzy"];$config = Configuration::instance(); print $config["Binzy"]; $config['Jasmin'] = "Binzy's Lover"; // config 2 $config2 = Configuration::instance(); print $config2['Jasmin'];
来源:http://www.tulaoshi.com/n/20160129/1491311.html
看过《ArrayAccess接口介绍》的人还看了以下文章 更多>>