php预定义数组,PHP预定义接口-数组式访问ArrayAccess

PHP有6个预定义接口。

bVbEoQ4

其中,数组式访问,即ArrayAccess。

简单来说,这个接口的作用是让我们可以像访问数组一样访问对象。

接口源代码:

/**

* Interface to provide accessing objects as arrays.

* @link http://php.net/manual/en/class.arrayaccess.php

*/

interface ArrayAccess {

/**

* Whether a offset exists

*/

public function offsetExists($offset);

/**

* Offset to retrieve

*/

public function offsetGet($offset);

/**

* Offset to set

*/

public function offsetSet($offset, $value);

/**

* Offset to unset

*/

public function offsetUnset($offset);

}

可以看到接口中有四个方法

未实现ArrayAccess

/**

* 未实现ArrayAccess

*/

class Obj

{

public $attr = 'attr';

}

$obj = new Obj();

echo $obj->attr; //使用->调用对象的属性,没有问题 attr

echo $obj['attr']; //使用['']数组方式调用对象的属性,报错:Cannot use object of type Obj as array

错误:

bVbEoXO

实现ArrayAccess

/**

* 实现ArrayAccess

*/

class Obj implements ArrayAccess

{

//检测属性值是否存在

public function offsetExists( $offset )

{

echo "offsetExists() $offset
";

}

//获取属性

public function offsetGet( $offset )

{

echo "offsetGet() $offset
";

}

//设置属性值

public function offsetSet( $offset, $value )

{

echo "offsetSet() $offset = $value
";

}

//删除属性值

public function offsetUnset( $offset )

{

echo "offsetUnset() $offset
";

}

}

$obj = new Obj();

isset($obj['attr']); //offsetExists() attr

$obj['attr']; //offsetGet() attr

$obj['attr'] = '123'; //offsetSet() attr = 123

unset($obj['attr']); //offsetUnset() attr

框架中常规用法

/**

* 框架中常规用法

*/

class Obj implements ArrayAccess

{

private $data = [

'attr' => '123'

];

//检测属性值是否存在

public function offsetExists( $offset )

{

return isset( $this->data[$offset] );

}

//获取属性

public function offsetGet( $offset )

{

return $this->data[$offset];

}

//设置属性值

public function offsetSet( $offset, $value )

{

$this->data[$offset] = $value;

}

//删除属性值

public function offsetUnset( $offset )

{

unset( $this->data[$offset] );

}

}

$obj = new Obj();

var_dump( isset($obj['attr']) ); //true

var_dump( $obj['attr'] ); //123

$obj['attr'] = '321';

var_dump( $obj['attr'] ); //321

unset($obj['attr']);

var_dump( isset($obj['attr']) ); //false

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值