Assign type to parameters

Asked

Viewed 419 times

12

It is possible to assign types for the parameters in functions in PHP?

Example:

public function random(int $length) {
  // ...
}

3 answers

12


It is possible partially through the so-called hinting type. You can only use complex types, like objects, arrays or flame types (Amble). Cannot use scalar types as is the case with int or string which loses much of the advantage.

Still the support given by the compiler is limited. Remember that language is dynamic and it is not always possible to guarantee everything you want without loss of flexibility.

There’s information that PHP 7 would have this expanded (in fact it happened, especially in 7.4), after all Hack, which is a new competitor, allows the so-called type Specification quite broadly (changes the name in PHP as well).

  • Or the SplType, how I answered :)

  • To complement: PHP 7 already accepts http://php.net/manualen/functions.arguments.php#functions.arguments.type-declaration

9

In PHP 5 the possibility of defining the type was opened (Type) of the function arguments, 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 isn’t supported.

Free translation:

Suggestions for Type may be of the object and array since version 5.1. More traditional type suggestions like int or string are not supported.

This possibility is already discussed a long time ago but has not yet been implemented.

3

With quoted by @Maniero, it is not possible to assign type induction to a function or method when it comes to scalar values.

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

So you could do something like

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

Then we would be limited to the following statement:

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

I do not believe that it is advantageous to do such a thing, but that is only an information response.

Updating

The above refers only to versions prior to PHP 5.6. For versions equal to or higher than PHP 7.0, it is possible to set the type of the parameter and return expected by the function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.