Home >Backend Development >PHP Tutorial >New features in PHP 7: type declarations

New features in PHP 7: type declarations

怪我咯
怪我咯Original
2017-07-14 14:09:111376browse

PHP7 will be a major version update of the PHP scripting language. It will also bring significant performance improvements and new features, as well as improve some outdated functions. This release will focus on performance enhancements and originate from the phpng branch of the PHP version tree.

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

##Function shape participating return type Declaring the demo is as follows

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

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

}

Above we defined a Demo class with one method in it. When declaring the method, we specified the

int $name that the function is required to receive. The parameters must be of type int. After the parentheses in the parameter list, we follow: int, which declares the return of our functionData type

$demo = new Demo();

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

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, we can achieve it by setting

declare(strict_type=1);

At this time, we Running the above code, you will get an

Uncaught Type Error

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

Statement:
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