您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

ArrayAccess 创建一个类数组对象

2024/11/1 2:26:26发布24次查看
/**
 * 单例模式实现类-->arrayaccess(数组式访问)接口
 *
 * @author flyer0126
 * @since 2012/4/27
 */
class single{
private $name;
private static $_instance = null;
private function __construct()
{
}
static function load()
{
if(null == self::$_instance)
{
self::$_instance = new single();
}
return self::$_instance;
}
public function setname($name)
{
$this->name = $name;
}
public function getname()
{
return $this->name;
}
}
$s = single::load();
$s->setname(jack);
echo $s->getname(); //jack
// 调整一下(继承arrayaccess && 实现4个方法)
class single implements arrayaccess
{
private $name;
private static $_instance = null;
private function __construct()
{
}
static function load()
{
if(null == self::$_instance)
{
self::$_instance = new single();
}
return self::$_instance;
}
public function setname($name)
{
$this->name = $name;
}
public function getname()
{
return $this->name;
}
/**
       * 实现四个方法
       * offsetexists(),用于标识一个元素是否已定义
       * offsetget(),用于返回一个元素的值
       * offsetset(),用于为一个元素设置新值
       * offsetunset(),用于删除一个元素和相应的值
      **/
public function offsetset($offset, $value) 
{
if (is_null($offset)) 
{
$this->container[] = $value;

else 
{
$this->container[$offset] = $value;
}
}
public function offsetget($offset) 
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
public function offsetexists($offset) 
{
return isset($this->container[$offset]);
}
public function offsetunset($offset) 
{
unset($this->container[$offset]);
}
}
$s = single::load();
$s->setname(jack);
$s[name] = mike;
echo $s->getname(); //jack
echo $s[name]; //mike
print_r($s);
/**
single object
(
    [name:single:private] => jack
    [container] => array
        (
            [name] => mike
        )
)
**/
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product