Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typed Arrays #17134

Closed
alisson-acioli opened this issue Dec 12, 2024 · 1 comment
Closed

Typed Arrays #17134

alisson-acioli opened this issue Dec 12, 2024 · 1 comment

Comments

@alisson-acioli
Copy link

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.

@damianwadley
Copy link
Member

This idea has come up many times before, such as in #15795 and #14384 and #13398, as well as through concepts like generics (array<T>) and pattern matching ($var is string[]). I think the most recent conversation on the internals mailing list was this one (also here?).
The summary is that support for typed arrays has some potential problems with its implementation, but there are also some competing ideas that would provide the same sort of functionality in a different way.

@damianwadley damianwadley closed this as not planned Won't fix, can't repro, duplicate, stale Dec 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants