Skip to content

Typed Arrays #17134

@alisson-acioli

Description

@alisson-acioli

Description

Currently PHP works with typing as everyone knows:

<?php

function sum(int $a, int $b) : int {
    return $a + $b;
}

What I would like to know is if it is possible to type an array with the type of a class for example (or another interface, enum, etc.) as this would help the IDE to recognize the methods and properties of the class.

An example would be:

<?php

class Person {
    public string $name;
    public int $age;

    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

function createMultiplePerson(array $people) : array<Person> {
    $result = [];
    foreach($people as $person) {
        $result[] = new Person($person['name'], $person['age']);
    }
    return $result;
}

$people = [
    ['name' => 'John', 'age' => 30],
    ['name' => 'Jane', 'age' => 25],
    ['name' => 'Doe', 'age' => 40]
];

$people = createMultiplePerson($people);

echo $people[0]->name;
echo $people[0]->age;

So when writing the code, the IDE would automatically complete the methods and properties of the Person class (name and age)

I don't know if the implementation of this is already under discussion or not, but I would like to leave this suggestion here for the community.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions