加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 当对象被转换为数组时如何返回特殊值?

发布时间:2020-12-13 17:16:29 所属栏目:PHP教程 来源:网络整理
导读:有一个神奇的方法__toString,如果一个对象在一个字符串上下文中使用或者被转换为这样的对象,它将被触发,例如, ?php class Foo { public function __toString() { return 'bar'; } } echo (string) new Foo(); // return 'bar'; 是否存在类似的函数,当一个对
有一个神奇的方法__toString,如果一个对象在一个字符串上下文中使用或者被转换为这样的对象,它将被触发,例如,

<?php 

class Foo {
    public function __toString() { 
        return 'bar'; 
  } 
} 

echo (string) new Foo(); // return 'bar';

是否存在类似的函数,当一个对象进入(数组)时会被触发?

解决方法

不,但是有 ArrayAccess接口,它允许您将类用作数组.要获得循环功能,您需要连接 IteratorAggregateIterator.如果您使用的是内部数组,前者更容易使用,因为您只需要覆盖一个方法(提供 ArrayIterator的实例),但是后者允许您对迭代进行更精细的控制.

例:

class Messages extends ArrayAccess,IteratorAggregate {
    private $messages = array();

    public function offsetExists($offset) {
        return array_key_exists($offset,$this->messages);
    }

    public function offsetGet($offset) {
        return $this->messages[$offset];
    }

    public function offsetSet($offset,$value) {
        $this->messages[$offset] = $value;
    }

    public function offsetUnset($offset) {
        unset($this->messages[$offset]);
    }

    public function getIterator() {
        return new ArrayIterator($this->messages);
    }
}

$messages = new Messages();
$messages[0] = 'abc';
echo $messages[0]; // 'abc'

foreach($messages as $message) { echo $message; } // 'abc'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读