ArrayAccess 建立一個類數組對象

來源:互聯網
上載者:User
/**

* 單例模式實作類別-->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

)


)

**/

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.