Table of Contents
1. ?? 运算符(NULL 合并运算符)
2. 函数返回值类型声明
3. 标量类型声明
4. use 批量声明
5. 其他的特性
Home Backend Development PHP Tutorial PHP 7 的几个新特性

PHP 7 的几个新特性

Jun 20, 2016 pm 12:46 PM

1. ?? 运算符(NULL 合并运算符)

把这个放在第一个说是因为我觉得它很有用。用法:

$a = $_GET['a'] ?? 1;
Copy after login

它相当于:

<?phpif (empty($_GET['a'])) $a = 1;
Copy after login

我们知道三元运算符是可以这样用的:

$a ?: 1
Copy after login

但是这是建立在 $a 已经定义了的前提上。新增的 ?? 运算符可以简化判断。

2. 函数返回值类型声明

官方文档提供的例子(注意 ... 的边长参数语法在 PHP 5.6 以上的版本中才有):

<?phpfunction arraysSum(array ...$arrays): array{    return array_map(function(array $array): int {        return array_sum($array);    }, $arrays);}print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));
Copy after login

从这个例子中可以看出现在函数(包括匿名函数)都可以指定返回值的类型。

这种声明的写法有些类似于 swift:

func sayHello(personName: String) -> String {    let greeting = "Hello, " + personName + "!"    return greeting}
Copy after login

这个特性可以帮助我们避免一些 PHP 的隐式类型转换带来的问题。在定义一个函数之前就想好预期的结果可以避免一些不必要的错误。

不过这里也有一个特点需要注意。PHP 7 增加了一个 declare 指令:strict_types,既使用严格模式。

使用返回值类型声明时,如果没有声明为严格模式,如果返回值不是预期的类型,PHP 还是会对其进行强制类型转换。但是如果是严格模式, 则会出发一个 TypeError 的 Fatal error。

强制模式:

<?phpfunction foo($a) : int{    return $a;}foo(1.0);
Copy after login

以上代码可以正常执行,foo 函数返回 int 1,没有任何错误。

严格模式:

<?phpdeclare(strict_types=1);function foo($a) : int{    return $a;}foo(1.0);# PHP Fatal error:  Uncaught TypeError: Return value of foo() must be of the type integer, float returned in test.php:6
Copy after login

在声明之后,就会触发致命错误。

是不是有点类似与 js 的 strict mode?

3. 标量类型声明

PHP 7 中的函数的形参类型声明可以是标量了。在 PHP 5 中只能是类名、接口、array 或者 callable (PHP 5.4,即可以是函数,包括匿名函数),现在也可以使用 string、int、float和 bool 了。

官方示例:

<?php// Coercive modefunction sumOfInts(int ...$ints){    return array_sum($ints);}var_dump(sumOfInts(2, '3', 4.1));
Copy after login

需要注意的是上文提到的严格模式的问题在这里同样适用:强制模式(默认,既强制类型转换)下还是会对不符合预期的参数进行强制类型转换,严格模式下则触发 TypeError 的致命错误。

4. use 批量声明

PHP 7 中 use 可以在一句话中声明多个类或函数或 const 了:

<?phpuse some\namespace\{ClassA, ClassB, ClassC as C};use function some\namespace\{fn_a, fn_b, fn_c};use const some\namespace\{ConstA, ConstB, ConstC};
Copy after login

但还是要写出每个类或函数或 const 的名称(并没有像 python 一样的 from some import * 的方法)。

需要留意的问题是:如果你使用的是基于 composer 和 PSR-4 的框架,这种写法是否能成功的加载类文件?

5. 其他的特性

其他的一些特性我就不一一介绍了,有兴趣可以查看官方文档:

http://php.net/manual/en/migration70.new-features.php

简要说几个:

  • PHP 5.3 开始有了匿名函数,现在又有了匿名类了;

  • define 现在可以定义常量数组;

  • 闭包( Closure)增加了一个 call 方法;

  • 生成器(或者叫迭代器更合适)可以有一个最终返回值(return),也可以通过 yield from 的新语法进入一个另外一个生成器中(生成器委托)。

生成器的两个新特性(return 和 yield from)可以组合。具体的表象大家可以自行测试。PHP 7 现在已经到 RC5 了,最终的版本应该会很快到来。

最后打个小广告:

5pyJ5oSP57uE5bu65LiA5Liq5LiN5rC055qEUEhQ55qEUVHnvqTvvJozMDU2MTEwODjvvIzmrKLov47liqDlhaXjgII=

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in Laravel Notifications in Laravel Mar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles