Home Backend Development PHP Tutorial PHP 7的一些引人注目的新特性简单介绍_PHP

PHP 7的一些引人注目的新特性简单介绍_PHP

May 28, 2016 pm 01:13 PM
php characteristic

1. ?? 运算符(NULL 合并运算符)
把这个放在第一个说是因为我觉得它很有用。用法:

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

它相当于:

<&#63;php
$a = isset($_GET['a']) &#63; $_GET['a'] : 1;
Copy after login

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

$a &#63;: 1
Copy after login

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

2. 函数返回值类型声明
官方文档提供的例子(注意 ... 的边长参数语法在 PHP 5.6 以上的版本中才有):

<&#63;php
function 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。

强制模式:

<&#63;php
function foo($a) : int
{
  return $a;
}
foo(1.0);
Copy after login

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

严格模式:

<&#63;php
declare(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 了。

官方示例:

<&#63;php
// Coercive mode
function sumOfInts(int ...$ints)
{
  return array_sum($ints);
}
var_dump(sumOfInts(2, '3', 4.1));
Copy after login

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

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

<&#63;php
use 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 的框架,这种写法是否能成功的加载类文件?其实是可以的,composer 注册的自动加载方法是在类被调用的时候根据类的命名空间去查找位置,这种写法对其没有影响。

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 了,最终的版本应该会很快到来。

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles