PHP SPL - is there any interface or class to control what happens when casting to array?

615 views Asked by At

So by implementing Iterator, ArrayAccess, and Countable built-in interfaces, we have control over what happens inside an object when it's used in foreach loops or if a property is accessed as if it were an array index ($object['id']).

For example, if you wanted, you could set it up so $object['version'] += 1 could automatically increment version field in the database.

What's missing is casting the object to array. Is there any interface or class that allows control over what happens when you do: (array) $object? Any built-in interface or class at all, no matter how obscure? For example: if I wanted (array) $object to return $this->propertyArray instead of the normal object to array conversion of dumping all public object properties?

Note: something like requiring calling $object->toArray() by method name doesn't count, as the idea is to minimize the outside differences between an array and object as much as possible.

2

There are 2 answers

1
Mr Coder On BEST ANSWER

no there is not , because toArray() is not an magic function like __toString(); where casting works e.g

$foo = (string) $myObect;

you have to specify toArray() and inside it return your array , may be in future __toArray() might come.

1
powtac On

You could add a method like this

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

See here. Or check SplFixedArray::toArray.