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

Detailed introduction to the new features of PHP7

怪我咯
Release: 2023-03-12 18:14:02
Original
1232 people have browsed it

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template