ArrayAccess creates an array-like object

巴扎黑
Release: 2016-11-23 13:38:36
Original
1760 people have browsed it

/**

* Singleton mode implementation class -->ArrayAccess (array access) interface

*

* @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;

}

/**

                                                                                                                                    to ’ s

  ’ ’ s ’ s ’ s to 1's ’         out out out out off out out through through ‐ to ‐ ‐ ‐ ‐ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ‐ ​ ​ ​ ​ ​Value

                                                                                                                              */

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

        )

)

**/


Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!