New features in PHP 7: type declarations

怪我咯
Release: 2023-03-13 22:16:01
Original
1213 people have browsed it

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 袁超  */ 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 the

int $namethat 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 型参数,也能通过检查
Copy after login

In the above example, we What is passed is a

floattype 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);
Copy after login

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!

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!