Home Backend Development PHP Tutorial Detailed introduction to the new features of PHP7

Detailed introduction to the new features of PHP7

Jul 05, 2017 am 10:28 AM
php php7 characteristic

This article mainly introduces information about the new features of PHP7. Here we have compiled detailed information and simple implementation codes to help you learn and refer to the new features. Interested friends can refer to

Learning New Features of PHP

The project I did recently used php7, but I feel that there are many new features that are not used. Just want to summarize some new features that may be used. The environment used before was php5.4. All the features of php5.5 and php5.6 will also be summarized. Here I only list the features that I think may be used in the project. The main content comes from the appendix of the PHP manual.

Generators (PHP 5 >= 5.5.0, PHP 7)

Supports generators by adding the yield keyword. Generators provides a simpler The method implements the iterator and does not need to implement the Iterator interface.

<?php
function xrange($start, $limit, $step = 1) {
 for ($i = $start; $i <= $limit; $i += $step) {
  yield $i;
 }
}

echo &#39;Single digit odd numbers: &#39;;

/* 注意保存在内存中的数组绝不会被创建或返回 */
foreach (xrange(1, 9, 2) as $number) {
 echo "$number ";
}
Copy after login

The above routine will output:

Single digit odd numbers: 1 3 5 7 9

Click the generator for details

Add finally keyword (PHP 5 >= 5.5.0, PHP 7)

try-catch now supports finally

foreach now supports list () (PHP 5 >= 5.5.0, PHP 7)

The foreach control structure now supports separating nested arrays into separate variables via the list() construct. For example:

<?php
$array = [
 [1, 2],
 [3, 4],
];

foreach ($array as list($a, $b)) {
 echo "A: $a; B: $b\n";
}
?>
Copy after login

The above routine will output:

A: 1; B: 2
A: 3; B: 4

array_column (PHP 5 >= 5.5.0, PHP 7)

array_column — Returns a specified column in an array

Use Expression definition constants (PHP 5 >= 5.6.0, PHP 7)

In previous PHP versions, you had to use static values ​​to define constants, declare properties, and specify Function parametersDefault value. You can now use numeric expressions including numbers, string literals, and other constants to define constants, declare properties, and set default values ​​for function parameters.

<?php
const ONE = 1;
const TWO = ONE * 2;

class C {
 const THREE = TWO + 1;
 const ONE_THIRD = ONE / self::THREE;
 const SENTENCE = &#39;The value of THREE is &#39;.self::THREE;

 public function f($a = ONE + self::THREE) {
  return $a;
 }
}

echo (new C)->f()."\n";
echo C::SENTENCE;
?>
Copy after login

The above routine will output:

4

The value of THREE is 3

Now you can pass the const keyword to define a constant of type array.

<?php
const ARR = [&#39;a&#39;, &#39;b&#39;];

echo ARR[0];
?>
Copy after login

The above routine will output:

a

Use... operator to define a variable-length parameter function (PHP 5 >= 5.6. 0, PHP 7)

You can now use the... operator to implement variable-length parameter functions without relying on func_get_args().

<?php
function f($req, $opt = null, ...$params) {
 // $params 是一个包含了剩余参数的数组
 printf(&#39;$req: %d; $opt: %d; number of params: %d&#39;."\n",
   $req, $opt, count($params));
}

f(1);
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);
f(1, 2, 3, 4, 5);
?>
Copy after login

The above routine will output:

$req: 1; $opt: 0; number of params: 0
$req: 1; $opt: 2; number of params : 0
$req: 1; $opt: 2; number of params: 1
$req: 1; $opt: 2; number of params: 2
$req: 1; $opt: 2 ; number of params: 3

Use... operator for parameter expansion (PHP 5 >= 5.6.0, PHP 7)

When calling the function When using... operator, arrays and iterable objects are expanded into function parameters. In other programming languages, such as Ruby, this is called the concatenation operator.

<?php
function add($a, $b, $c) {
 return $a + $b + $c;
}

$operators = [2, 3];
echo add(1, ...$operators);
?>
Copy after login

The above routine will output:

6

use function and use const (PHP 5 >= 5.6.0, PHP 7)

The use operator has been extended to support importing external functions and constants into the class. The corresponding structures are use function and use const.

<?php
namespace Name\Space {
 const FOO = 42;
 function f() { echo FUNCTION."\n"; }
}

namespace {
 use const Name\Space\FOO;
 use function Name\Space\f;

 echo FOO."\n";
 f();
}
?>
Copy after login

The above routine will output:

42

Name\Space\f

debugInfo() (PHP 5 > = 5.6.0, PHP 7)

Add debugInfo(), which can be used to control the attributes and values ​​to be output when using var_dump() to output objects.

<?php
class C {
 private $prop;

 public function construct($val) {
  $this->prop = $val;
 }

 public function debugInfo() {
  return [
   &#39;propSquared&#39; => $this->prop ** 2,
  ];
 }
}

var_dump(new C(42));
?>
Copy after login

The above routine will output:

object(C)#1 (1) {
 ["propSquared"]=>
 int(1764)
}
Copy after login

Scalar type declaration (PHP 7)

There are two modes for scalar type declaration: Enforcement (default) and strict mode. The following type parameters are now available (either in forced or strict mode): string, int, float, and bool. They extend other types introduced in PHP5: class names, interfaces, arrays and callback types.

<?php
// Coercive mode
function sumOfInts(int ...$ints)
{
 return array_sum($ints);
}

var_dump(sumOfInts(2, &#39;3&#39;, 4.1));
Copy after login

The above routine will output:

int(9)

To use strict mode, a declare declaration directive must be placed at the top of the file. This means that scalars are strictly declared configurable on a file basis. This directive not only affects the type declaration of the parameters, but also affects the return value declaration of the function (see return value type declaration, built-in PHP functions and PHP functions loaded in extensions)

Return value type declaration (PHP 7)

PHP 7 adds support for return type declaration. Similar to the parameter type declaration, the return type declaration specifies the type of the function's return value. The available types are the same as those available in the parameter declaration.

<?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

The above routine will output:

Array
(
[0] => 6
[1] => 15
[2] => 24
)

null coalescing operator (PHP 7)

由于日常使用中存在大量同时使用三元表达式和 isset()的情况, 我们添加了null合并运算符 (??) 这个语法糖。如果变量存在且值不为NULL, 它就会返回自身的值,否则返回它的第二个操作数。

<?php
// Fetches the value of $_GET[&#39;user&#39;] and returns &#39;nobody&#39;
// if it does not exist.
$username = $_GET[&#39;user&#39;] ?? &#39;nobody&#39;;
// This is equivalent to:
$username = isset($_GET[&#39;user&#39;]) ? $_GET[&#39;user&#39;] : &#39;nobody&#39;;

// Coalesces can be chained: this will return the first
// defined value out of $_GET[&#39;user&#39;], $_POST[&#39;user&#39;], and
// &#39;nobody&#39;.
$username = $_GET[&#39;user&#39;] ?? $_POST[&#39;user&#39;] ?? &#39;nobody&#39;;
?>
Copy after login

太空船操作符(组合比较符)(PHP 7)

太空船操作符用于比较两个表达式。当$a小于、等于或大于$b时它分别返回-1、0或1。 比较的原则是沿用 PHP 的常规比较规则进行的。

<?php
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
 
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
?>
Copy after login

通过 define() 定义常量数组 (PHP 7)

Array 类型的常量现在可以通过 define() 来定义。在 PHP5.6 中仅能通过 const 定义。

<?php
define(&#39;ANIMALS&#39;, [
 &#39;dog&#39;,
 &#39;cat&#39;,
 &#39;bird&#39;
]);

echo ANIMALS[1]; // outputs "cat"
?>
Copy after login

匿名类 (PHP 7)

现在支持通过new class 来实例化一个匿名类,这可以用来替代一些“用后即焚”的完整类定义。

<?php
interface Logger {
 public function log(string $msg);
}

class Application {
 private $logger;

 public function getLogger(): Logger {
   return $this->logger;
 }

 public function setLogger(Logger $logger) {
   $this->logger = $logger;
 }
}

$app = new Application;
$app->setLogger(new class implements Logger {
 public function log(string $msg) {
  echo $msg;
 }
});

var_dump($app->getLogger());
?>
Copy after login

以上例程会输出:

object(class@anonymous)#2 (0) {
}

Closure::call() (PHP 7)

Closure::call() 现在有着更好的性能,简短干练的暂时绑定一个方法到对象上闭包并调用它。

<?php
class A {private $x = 1;}

// Pre PHP 7 code
$getXCB = function() {return $this->x;};
$getX = $getXCB->bindTo(new A, &#39;A&#39;); // intermediate closure
echo $getX();

// PHP 7+ code
$getX = function() {return $this->x;};
echo $getX->call(new A);
Copy after login

以上例程会输出:

1
1

为unserialize()提供过滤 (PHP 7)

这个特性旨在提供更安全的方式解包不可靠的数据。它通过白名单的方式来防止潜在的代码注入。

<?php
// converts all objects into PHP_Incomplete_Class object
$data = unserialize($foo, ["allowed_classes" => false]);

// converts all objects into PHP_Incomplete_Class object except those of MyClass and MyClass2
$data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]);

// default behaviour (same as omitting the second argument) that accepts all classes
$data = unserialize($foo, ["allowed_classes" => true]);
Copy after login

Group use declarations (PHP 7)

从同一 namespace 导入的类、函数和常量现在可以通过单个 use 语句 一次性导入了。

<?php

// Pre PHP 7 code
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;

use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;

use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;

// PHP 7+ code
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

The above is the detailed content of Detailed introduction to the new features of PHP7. For more information, please follow other related articles on the PHP Chinese website!

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

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

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.

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