There have been several attempts to introduce a standard toArray method or interface in PHP:
- The first attempt was in 2012, when an RFC proposed adding several magic methods to PHP, including
__toArray,__toInt(),__toFloat(),__toScalar(), and__toBool(). This proposal failed before reaching the voting stage due to concerns about implementation details and lack of consensus. - In 2019, a separate RFC specifically focused on introducing only a
__toArraymethod for objects. Unlike the broader 2012 proposal, this RFC aimed to standardize array conversion alone, but it also failed before reaching the voting stage due to lack of support and unresolved concerns—particularly that the__toArraymethod did not specify what kind of array should be returned (e.g., associative or indexed), nor whether nested arrays or objects were allowed as values. One of the main unresolved questions was how to specify or standardize the format of the returned array in a way that would suit all use cases. - Over the years, various frameworks and libraries (such as Laravel's illuminate/contracts) have introduced their own
toArrayconventions, but these are not universal and often come with additional dependencies. - As of now, neither PHP itself nor the PHP-FIG group has adopted an official standard for object-to-array conversion.
This package was created to address this gap: it provides a minimal Composer package containing only the ToArrayInterface. Use it when you need to ensure an object can be converted to an array via a toArray method, without introducing unnecessary dependencies.
To install and use this package, use Composer:
composer require imponeer/toarray-interfaceAlternatively, manually include the files from the src/ directory.
Note: For PHP 5 projects, use version 1.0 of this library.
use Imponeer\ToArrayInterface;
class DummyObject implements ToArrayInterface {
/**
* Converts object to array
*
* @return array<string, mixed>
*/
public function toArray(): array {
return [
'hash' =>