Detailed descriptions of function types in various PHP versions and php function declarations

Source: Internet
Author: User
Tags scalar

Detailed descriptions of function types in various PHP versions and php function declarations

PHP7 began to support scalar type declarations. Strong-type languages have a strong taste. When using this feature, we step on two pitfalls: declare boolean at one time, and declare double at most. To avoid continuing to make similar mistakes in the future, I will repeat the official document once. This article summarizes the usage of the PHP function type declaration after reading it.

In terms of syntax, the function definition of PHP goes through several periods:

Ancient Times (PHP 4)

Defining a function is very simple. Use the function name (args) {body} syntax declaration. Parameter and return value types cannot be specified. There are infinite possibilities for parameter and return value types. This is the most common function declaration method so far.

Array and reference type parameter value declaration (PHP 5)

Arrays, classes, interfaces, and callable can be used in function declaration. Starting from 5.6, constants (including class constants) are supported as default parameters, and parameter arrays (with ellipsis... Prefix ). For example:

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

Note: If the parameter value may be null, null must be the default value of the parameter. Otherwise, an error occurs during the call. For example:

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

Scalar type and return value declaration (PHP 7)

The function officially supports the declaration of scalar type (int, bool, float, etc.) and return value type (the same type can be declared. Since this version, writing PHP has the feeling of writing java.

Unfortunately, if the return value of a function may be null, the type of the return value 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 is still null, an error occurs}

The parameter and return value can be null and void return type declaration (PHP 7.1)

When the type of the parameter and return value may be null, question mark (?) is used before the type (?) Modification can solve the null Value Problem (not conflict with the default parameter). The type declaration adds iterable, and also supports the 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); // The function declares the parameter and does not provide the default parameter, when a parameter is not input during the call, an error occurs. // change the function declaration to getModel (? Int $ id = 100) {}, you can choose not to pass the parameter $ foo-> getModel ();

When the return value of a function is void, the return value of the function body cannot be of 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 and the function type declaration have been very complete (although not much is used in practice ).

Let's talk about the pitfalls in practice. Parameter and return value types can be declared as follows:

  1. Class/interface
  2. Self can only be used in its own method
  3. Array
  4. Bool
  5. Callable
  6. Int
  7. Float
  8. String
  9. Iterable

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

This is also a bit painful for PHP. In common use, the double and float keywords are almost the same. For example, doubleval is the alias of floatval, is_double is the alias of is_float, and the (double) and (float) effects are the same during conversion. However, the type declaration won't work here. The same situation occurs on bool and boolean.

Summary

Currently, PHP 7.2 stable version has been released. We recommend that you use PHP 7.1 and later versions as much as possible in new projects. The Declaration type is recommended to Write clear and maintainable code. We recommend that you use null for reference type or string. Do not use null for parameters of the int/float type. Func_get_argc and other functions. Do not use them unless necessary.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.