(PHP 5 >= 5.0.0, PHP 7)
Examples:
Basic usage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | <?php class obj implements ArrayAccess { private $container = array (); public function __construct() { $this ->container = array ( "one" => 1, "two" => 2, "three" => 3, ); } public function offsetSet( $offset , $value ) { if ( is_null ( $offset )) { $this ->container[] = $value ; } else { $this ->container[ $offset ] = $value ; } } public function offsetExists( $offset ) { return isset( $this ->container[ $offset ]); } public function offsetUnset( $offset ) { unset( $this ->container[ $offset ]); } public function offsetGet( $offset ) { 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 [] = 'Append 1' ; $obj [] = 'Append 2' ; $obj [] = 'Append 3' ; print_r( $obj ); ?> |
The above example will output something similar to:
bool(true) int(2) bool(false) string(7) "A value" obj Object ( [container:obj:private] => Array ( [one] => 1 [three] => 3 [two] => A value [0] => Append 1 [1] => Append 2 [2] => Append 3 ) )