如何在将对象转换为数组时返回特殊值?

时间:2013-05-04 18:45:45

标签: php

有一种魔术方法__toString,如果在字符串上下文中使用对象或将其转换为对象,则会触发该方法,例如。

<?php 

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

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

当一个对象进入(array)时是否会触发类似的函数?

2 个答案:

答案 0 :(得分:2)

不,但是有ArrayAccess接口,允许您将类用作数组。要获得循环功能la foreach,您需要界面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'

答案 1 :(得分:2)

这可能不是您所期望的那样,因为您所期望的不是PHP的语言功能(不幸的是),但这里有一个众所周知的解决方法:

使用get_object_vars()

$f = new Foo();
var_dump(get_object_vars($f));

它将返回一个关联数组,其属性名称为索引及其值。检查此示例:

class Foo {

    public $bar = 'hello world';

    // even protected and private members will get exported:
    protected $test = 'I\'m protected';
    private $test2 = 'I\'m private';


    public function toArray() {
        return get_object_vars($this);
    }   

}

$f = new Foo();
var_dump($f->toArray());

输出:

array(2) {
  'bar' =>
  string(11) "hello world"
  'test' =>
  string(13) "I'm protected"
  'test2' =>
  string(13) "I'm private"
}