php Converting an object implementing ArrayAccess in array

When you implement the _toString method on a class, you are able to convert the object in string

$string =(string) $object

Is there an equivalent for converting in array

$array=(array) $object

From what I have tested, with this code, the attributes of the objet are transformed in index of the array, even if this object implement ArrayAccess.

I expected that casting an object with array access, I would obtain an array thith the same values I could access with the object

public function MyObject implements ArrayAccess{
     private $values;
     public function __construct(array $values){
        $this->values=$values;
     }
     public function offsetSet($name,$value){
        $this->values[$name]=$value;
     }
     //etc...
}

$myObject=new MyObject(array('foo'=>'bar');

$asArray=(array)$myObject;

print_r($asArray);
// expect array('foo'=>'bar')
// but get array('MyObjectvalues'=>array('foo'=>'bar'));

I also Notice that the native ArrayObject class has a the behavior I expected


No, there is no magic function to cast object as array.

ArrayObject is implemented with C and has weird specific behaviors.

Implement custom method asArray and use it.

链接地址: http://www.djcxy.com/p/64864.html

上一篇: 在使用3个foreach时未定义的属性

下一篇: php在数组中转换实现ArrayAccess的对象