標籤:
<?phpclass obj implements arrayaccess { private $container = array(); public function __construct () { $this -> container = array( "one" => 1 , "two" => 2 , "three" => 3 , ); } public function offsetSet ( $offset , $value ) { echo ‘把對象當數組一樣賦值的時候執行,此方法‘; if ( is_null ( $offset )) { $this -> container [] = $value ; } else { $this -> container [ $offset ] = $value ; } } public function offsetExists ( $offset ) { echo ‘把對象當數組一樣檢測是否定義的時候執行,此方法‘; return isset( $this -> container [ $offset ]); } public function offsetUnset ( $offset ) { echo ‘把對象當數組一樣刪除元素的時候執行,此方法‘; unset( $this -> container [ $offset ]); } public function offsetGet ( $offset ) { echo ‘把對象當數組一樣擷取某元素的時候執行,此方法‘; return isset( $this -> container [ $offset ]) ? $this -> container [ $offset ] : null ; } }$obj = new obj ;var_dump (isset( $obj [ "two" ]));var_dump ( $obj [ "two" ]);unset( $obj [ "two" ]);var_dump (isset( $obj [ "two" ]));$obj [ "two" ] = "A value" ;var_dump ( $obj [ "two" ]);$obj [‘a‘] = ‘Append 1‘ ;$obj [‘b‘] = ‘Append 2‘ ;$obj [‘c‘] = ‘Append 3‘ ;print_r ( $obj );
PHP預定義介面中 ArrayAccess 數組式提供者