Skip to content

About

PHP library that provides toArray interface, that could be used everywhere where you need to convert object into array and make sure that to that toArray function is because of same interface

Topics

Resources

Stars

5 stars

Watchers

3 watching

Forks

Repository files navigation

License GitHub release PHP Packagist

ToArray Interface

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 __toArray method 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 __toArray method 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 toArray conventions, 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.

Installation

To install and use this package, use Composer:

composer require imponeer/toarray-interface

Alternatively, manually include the files from the src/ directory.

Note: For PHP 5 projects, use version 1.0 of this library.

Example

use Imponeer\ToArrayInterface;

class DummyObject implements ToArrayInterface {

    /**
     * Converts object to array
     *
     * @return array<string, mixed>
     */
    public function toArray(): array {
        return [
            'hash' =>