Assign type to array in PHP

Question:

I know PHP is a weakly typed language. But is there any alternative way to "type" an array in PHP?

For example, I can do this below to force a function to receive a specific data type.

function exemplo(Classe $valor){
    // meu código aqui ...
}

However, I would like to know how to do something similar as it is done in Java (See below) with lists.

List<String> array = new ArrayList<>;

Is there a way to do this in PHP?

Answer:

It's not possible.

PHP was dynamically and weakly typed, basically nothing has a fixed type. All PHP arrays accept that any element has any type. You can mix at will. It is an inherent characteristic of this type of language. There is no syntax or option in the compiler that can force or even indicate what data type elements can have. That is, they will always be mixed according to the PHP definition.

Hack , which is an evolution of PHP created by Facebook, allows generics and " arrays " can be typed. Despite being based on PHP, it is another language.

It's partially possible in PHP since version 7, and in 7.4 this becomes stronger, but it's lamely done because it has the typeless legacy.

Scroll to Top