首页 > PHP教程 > PHP预定义接口的使用

PHP ArrayAccess(数组式访问)接口

PHP ArrayAccess(数组式访问)接口提供像访问数组一样访问对象的能力的接口

接口摘要:

ArrayAccess {

/* 方法 */

abstract public boolean offsetExists ( mixed $offset )

abstract public mixed offsetGet ( mixed $offset )

abstract public void offsetSet ( mixed $offset , mixed $value )

abstract public void offsetUnset ( mixed $offset )

}

提供像访问数组一样访问对象的能力的接口

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 );

PHP历史版本

关闭
感谢您的支持,我会继续努力!
扫码打赏,建议金额1-10元


提醒:打赏金额将直接进入对方账号,无法退款,请您谨慎操作。