Explanation of Type Declarations of Functions in PHP Versions

  • 2021-09-04 23:39:16
  • OfStack

PHP7 began to support scalar type declaration, and the taste of strongly typed language is strong. I stepped through two pits in the process of using this feature: once I declared boolean, and most recently I declared double. In order to avoid making similar mistakes in the future, the official documents were turned over once. This article is a summary of the use of type declaration of PHP function after reading it.

Syntactically, the function definition of PHP has gone through several periods:

Ancient Times (PHP 4)

Defining a function is very simple, using the syntax declaration of function name (args) {body}. You cannot specify parameter and return value types. There are unlimited possibilities for parameter and return value types. This is by far the most common way to declare functions.

Array and reference type parameter value declaration (PHP 5)

Arrays (array), classes (class), interfaces (interface), and functions (callable) can be used in function declarations. Beginning with 5.6, constants (including class constants) are supported as default parameters, as well as parameter arrays (prefixed with ellipsis …). For example:


function sum(...$numbers) {
  $sum = 0;
  foreach ($numbers as $number) {
    $sum += $number;
  }
  return $sum;
}

Note: If the value of the parameter may be null, null must be the default value of the parameter, otherwise an error will occur when invoked. For example:


function foo(array $arr = null) {
  ...
}

Scalar Type and Return Value Declaration (PHP 7)

Function formally supports scalar type (int, bool, float, etc.) and return value type (declarable types are the same as parameters) declarations. From this release, writing PHP feels like writing java.

Unfortunately, if the function return value is likely to be null, the return value type cannot be specified. For example:


function getModel() : Foo {
  if ($this->_model === null) {
     $this->_model = xxxx; // get from db or otherelse
  }
  return $this->_model;   //  If $this->_model Still null Error running 
}

Parameters and return values can be null and void return type declarations (PHP 7.1)

When the parameter and return value types are likely to be null, the type is preceded by a question mark (?) Modification, which can solve the problem of null value (does not conflict with default parameters); Type declaration adds iterable, and also supports void type return value. For example:


function getModel(?int $id) : ?Foo {
  if ($id !== null) {
    $this->_model = xxxx;
  } else {
    $this->_model = yyyy;
  }
  return $this->_model;
}
 
//  Call 
$foo->getModel(null);
$foo->getModel(100);
 
//  Function declares parameters and does not provide default parameters. If no parameters are passed in when called, an error will be raised 
//  Change the function declaration to  getModel(?int $id = 100) {} You can not pass parameters 
$foo->getModel();

When the return value of the function is void, the return of the function body cannot be followed by any type, or the return statement does not appear.


function test(array $arr) : void {
  if (!count($arr) {
    return;
  }
 
  array_walk($arr, function ($elem) {xxxx});
}

After reviewing the above history, we can see that PHP 7.1, the function type declaration is 10 points perfect (although it is not used much in practice).

Let's talk about the pit we stepped on in practice. The types available for parameter and return value type declarations are:

Class/interface self can only be used in its own way array bool callable int float string iterable

Note that boolean and double types are not in the list! Unless you define these two types, it is wrong to use them in parameters and return values!

This is also where PHP has a little egg pain. In common use, double and float are almost identical. For example, doubleval is an alias of floatval, is_double is an alias of is_float, and double and float have the same effect when converting. But not when it comes to type declarations, as is the case with bool and boolean.

Summarize

At present, the stable version of PHP 7.2 has been released, and it is recommended to use PHP 7.1 and subsequent versions as much as possible in new projects. In order to write clear and maintainable code, it is recommended to declare types. It is recommended to use null value only for reference type or string, and try not to use null for scalar type parameters such as int/float. func_get_argc and other functions, if not necessary, try not to use.


Related articles: