The new features in PHP 7: type declaration

Source: Internet
Author: User
In PHP7, a new feature that returns a type declaration has been introduced. Returns the type of a function return value specified by the type declaration. The following article mainly introduces the PHP 7 new characteristics of the type declaration of the relevant information, the article introduced in very detailed, the need for friends can refer to the following to see together.

Objective

PHP7 the type declaration to be possible, PHP 7 supports the type of formal parameter declaration of the following kinds of

    • Integral type

    • Floating point Type

    • String type

    • Boolean type

function form participating return type declaration demo is as follows

/** * @author Yuan Chao <yccphp@163.com> */class demo{/** * int $name is the formal parameter type declaration *: int is the return type declaration */Public Function age (int $age): int {return $age;}}

Above we define a Demo class, inside a method, when declaring a method, we specify that the int $name parameter required to receive the function must be of type int, after the argument list parenthesis, we follow: int, it declares the return data type of our function

$demo = new Demo (); $demo->age (10.23); We pass the float type parameter, and we can pass the check

In the example above, we're passing a float type parameter, but the code is still working.

This is because in PHP7, the parameter type description is not completely limited by default, which means that what we define is just a suggestion, not a full constraint

Of course, we can completely limit our implementation by setting

Declare (strict_type=1);

This time, we run the above code, then we get aUncaught Type Error

This change makes a lot of sense, so that when we do a number of projects with multiple people, there's no problem with parameter scrambling and not knowing what the function returns.

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.