Home > Backend Development > PHP Tutorial > Detailed explanation of the new features in PHP 7: type declaration

Detailed explanation of the new features in PHP 7: type declaration

怪我咯
Release: 2023-03-10 14:22:01
Original
1518 people have browsed it

In PHP7, a new feature, return type declaration has been introduced. A return type declaration specifies the type of value returned by a function. The following article mainly introduces you to the relevant information of the type declaration of the new features of PHP 7. The introduction in the article is very detailed. Friends in need can refer to it. Let’s take a look together.

Preface

PHP7 makes type declaration possible. The types of formal parameter type declaration supported by PHP 7 are as follows

  • Integer type

  • Floating point type

  • String type

  • Boolean type

The function shape participates in the return type declaration demo as follows

/**
 * @author 袁超 <yccphp@163.com>
 */
class Demo{

 /**
 * int $name 则是形参类型声明
 * : int 是返回类型声明
 */
 public function age(int $age) : int
 {
 return $age;
 }

}
Copy after login

Above we defined a Demo class with one method in it. When declaring the method, we specified int $name which requires that the parameters received by the function must be of type int. , after the parentheses in the parameter list, we follow: int, which declares the return data type of our function

$demo = new Demo();

$demo->age(10.23); // 我们传递的是 float 型参数,也能通过检查
Copy after login

In the above example, we What is passed is a float type parameter, but the code can still run normally

This is because in php7, the formal parameter type description is not completely restricted by default. It means that what we define is just a suggestion, not a complete constraint

Of course, we can completely restrict it, and we can achieve it by setting

declare(strict_type=1);
Copy after login

At this time, when we run the above code, we will get an Uncaught Type Error

This change is quite meaningful, so that when we do some projects involving multiple people, There will be no problems with parameters being passed randomly and not knowing what this function returns

The above is the detailed content of Detailed explanation of the new features in PHP 7: type declaration. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template