92

I am very happy with the new features in PHP 7. But I am confused on how to return an array of objects in PHP 7.

For example, we have a class Item, and we want to return an array of objects of this class from our function:

function getItems() : Item[] {
}

But it does not work this way.

0

4 Answers 4

104

You can type hint this way using docblocks.

PHP editor (IDE) like PhpStorm supports this very well and will properly resolve the class when iterating over such array.

/**
 * @return YourClass[]
 */
public function getObjects(): array

PHPStorm also supports nested arrays:

/**
 * @return YourClass[][]
 */
public function getObjects(): array

Newer versions of PHPStorm support phpstan/psalm format:

/**
 * @return array<int, YourObject>
 */
public function getObjects(): array

Or even generics:

/**
 * @template T of object
 * @param class-string<T> $className
 * @return array<array-key, T>
 */
public function getCollectionOf(string $className): array
6
  • 2
    yep, also suported by phpactor Jan 17, 2019 at 17:03
  • 3
    Works also in NetBeans.
    – jor
    Mar 15, 2019 at 10:36
  • 4
    Just FYI, this doesn't work with VSCode + Intelliphense extension Jun 25, 2019 at 20:54
  • 8
    I wouldn’t use anything else than PhpStorm.
    – Mike Doe
    Jun 25, 2019 at 21:12
  • 3
    Although I upvoted you for "use phpdocs", this is not about >Generics<. As the main principe of generics is "Type is going to be specified later, use generic symbol insted of true type for now". In the desire stated here, type is known at the time of writing code.
    – Reloecc
    Aug 7, 2020 at 11:04
89

I actually understand what you mean, but the answer unfortunately is that you can't do that. PHP7 lacks that kind of expressivity, so you can either declare your function to return "array" (a generic array) or you have to create a new class ItemArray which is an array of Item (but that meaning you will have to code it yourself).

There is currently no way to express "I want an array of Item" instances.

EDIT: As an added reference, here the "array of" RFC of what you wanted to do, it has been declined due to various reasons.

5
  • 20
    i thought moving to PHP 7 can help me to create a strict-typing code :/ Nov 19, 2016 at 13:37
  • 1
    I know, it is disappointing :( I added a reference to the RFC which talks exactly about the feature you asked about. It was declined.
    – Johnny
    Nov 19, 2016 at 13:42
  • 1
    @Johnny , I don't understand PHPs rfc voting method, there's no reasoning behind why they just deny stuff without a second glance, direct voting is not a good system for this Feb 13, 2020 at 11:32
  • 2
    For now we can only use custom classes implementing ArrayAccess and Iterator interfaces and some custom validation for inputs. Also RFC is from 2014 and it should be revisited. This will be one more step to typed arrays. Like in Java String[], int[].
    – user4494077
    Mar 10, 2020 at 22:00
  • 3
    That RFC is also very old and was proposed for php5.6. I think they should reconsider it now we are all heading towards strict typing it makes a lot more sense than it did back when it was initially proposed.
    – Brad
    Feb 17, 2021 at 1:02
13

The current version of PHP doesn't support a built-in type hinting for an array of objects, as there is no such data type as "an array of objects". A class name can be interpreted as a type in certain contexts, as well as array, but not both at a time.

Actually you can implement such kind of strict type hinting by creating a class based on the ArrayAccess interface, e.g.:

class Item
{
    protected $value;

    public function __construct($value)
    {
        $this->value = $value;
    }
}

class ItemsArray implements ArrayAccess
{
    private $container = [];

    public function offsetSet($offset, $value)
    {
        if (!$value instanceof Item) {
            throw new Exception('value must be an instance of Item');
        }

        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}


function getItems() : ItemsArray
{
    $items = new ItemsArray();
    $items[0] = new Item(0);
    $items[1] = new Item(2);
    return $items;
}

var_dump((array)getItems());

Output

array(2) {
  ["ItemsArrayitems"]=>
  array(0) {
  }
  ["container"]=>
  array(2) {
    [0]=>
    object(Item)#2 (1) {
      ["value":protected]=>
      int(0)
    }
    [1]=>
    object(Item)#3 (1) {
      ["value":protected]=>
      int(2)
    }
  }
}
3
  • 1
    this is a good one, but i prefer an automatic way, i hope they implement this feature in near future, thanks :) Nov 19, 2016 at 13:46
  • Thanks. One thing I noticed. Should it be private $container = []; instead of private $items = []; ?
    – kta
    Jun 8, 2019 at 9:10
  • @kta, you are correct. I've edited the answer. Thank you. Jun 8, 2019 at 9:43
1

It is not possible at the moment. But you can achieve your intended behavior with a custom array class


function getItems() : ItemArray {
  $items = new ItemArray();
  $items[] = new Item();
  return $items;
}

class ItemArray extends \ArrayObject {
    public function offsetSet($key, $val) {
        if ($val instanceof Item) {
            return parent::offsetSet($key, $val);
        }
        throw new \InvalidArgumentException('Value must be an Item');
    }
}

Thanks to bishop's answer here

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.