Last active
August 29, 2015 14:24
-
-
Save t301000/63e491cc04fb5ed78741 to your computer and use it in GitHub Desktop.
ArrayAccess example from php.net
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class obj implements arrayaccess { | |
private $container = array(); | |
//設定 $container | |
public function __construct() { | |
$this->container = array( | |
"one" => 1, | |
"two" => 2, | |
"three" => 3, | |
); | |
} | |
//設定 $container[$offset] = $value | |
//$offset未指定時則以數字索引賦值 | |
public function offsetSet($offset, $value) { | |
if (is_null($offset)) { | |
$this->container[] = $value; | |
} else { | |
$this->container[$offset] = $value; | |
} | |
} | |
//檢查$container[$offset]是否有值,回傳true false | |
public function offsetExists($offset) { | |
return isset($this->container[$offset]); | |
} | |
//unset $container[$offset] | |
public function offsetUnset($offset) { | |
unset($this->container[$offset]); | |
} | |
//取得$container[$offset]之值回傳 | |
public function offsetGet($offset) { | |
return isset($this->container[$offset]) ? $this->container[$offset] : null; | |
} | |
} | |
/* | |
* 此時 $obj 為一個物件 | |
* 其 container 屬性為陣列 ['one' => 1, 'two' => 2, 'three' => 3] | |
* | |
*/ | |
$obj = new obj; | |
var_dump(isset($obj["two"])); // bool(true) | |
var_dump($obj["two"]); // int(2) | |
unset($obj["two"]); | |
var_dump(isset($obj["two"])); // bool(false) | |
$obj["two"] = "A value"; | |
var_dump($obj["two"]); // string(7) "A value" | |
$obj[] = 'Append 1'; // $obj->container[0] = 'Append 1' | |
$obj[] = 'Append 2'; // $obj->container[1] = 'Append 2' | |
$obj[] = 'Append 3'; // $obj->container[2] = 'Append 3' | |
print_r($obj); | |
//obj Object | |
//( | |
// [container:obj:private] => Array | |
// ( | |
// [one] => 1 | |
// [three] => 3 | |
// [two] => A value | |
// [0] => Append 1 | |
// [1] => Append 2 | |
// [2] => Append 3 | |
// ) | |
//) | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment