Assign type to parameters

9

Is it possible to assign types to the parameters in functions in PHP?

Example:

public function random(int $length) {
  // ...
}
    
asked by anonymous 07.03.2015 / 23:30

3 answers

10

It is partially possible through the type hinting . You can only use complex types, such as objects, arrays Hack , which is a new competitor, allows the type specification quite extensively (it changes the name in PHP as well).

    
07.03.2015 / 23:40
7

In PHP 5 the possibility of defining the type ( Type ) of the function's arguments was opened, but only for objects / classes.

Following the documentation :

  

Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string is not supported.

Free translation:

  

Type hints can be of type object and array since version 5.1. More traditional type suggestions such as int or string are not supported.

This possibility is already discussed there is plenty of time but has not yet been implemented.

    
07.03.2015 / 23:39
1

As mentioned by @bigown, it is not possible to assign type induction to a function or method when it comes to scalar values.

I believe that the only way in PHP to force parameters of type scalar in PHP would be only of the Spl Type library.

So you could do something like

function soma(SplInt $a, SplInt $b) {
    return $a + $b;
}

Here we would limit ourselves to the following statement:

soma(new SplInt(3), new SplInt(5));

I do not think it is advantageous to do such a thing, but this is a response only to the level of information.

    
25.08.2015 / 17:42