Home Backend Development PHP Tutorial 深入浅析PHP7.0新特征(五大新特征)_php实例

深入浅析PHP7.0新特征(五大新特征)_php实例

Jun 07, 2016 pm 05:11 PM

截止到目前为止,PHP官方已经发布了php7的RC5版本,预计在11月份左右会发布第一个正式版本!现在来说php7的重大特性肯定已经是定型了,不会再有什么变动了。后续一些版本的迭代主要也就是修修bug,优化之类的。下面就来说话我们一直期待的php7.0五大新特征吧。

如果你使用的是基于 composer 和 PSR-4 的框架,这种写法是否能成功的加载类文件?其实是可以的,composer 注册的自动加载方法是在类被调用的时候根据类的命名空间去查找位置,这种写法对其没有影响。

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

# PHP Fatal error: Uncaught TypeError: Return value of foo() must be of the type integer, float returned in test.php:6

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

是不是有点类似与 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 了,最终的版本应该会很快到来。

以上所述是关于php7.0新特征的全部内容,希望本文介绍大家喜欢。

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)

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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

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.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles