最近看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