An article to help you understand the PHP 7.3 update

步履不停
Release: 2023-04-06 21:14:01
Original
5784 people have browsed it

An article to help you understand the PHP 7.3 update

PHP is still a strong competitor to other scripting languages, mainly due to the rapid updates of its core maintenance team.

Since the release of PHP 7.0, the community has witnessed the birth of many new features that have greatly improved the way developers apply PHP in their projects. Improving the performance and security of PHP applications is the main purpose of these improvements.

PHP recently achieved another milestone - released PHP 7.3. The new version brings some much-needed updates.

In this article, I will discuss the new PHP 7.3 features and updates. The good news is that you can install the new version yourself on your test server and check out the new features. But as the old saying goes, never use RC version updates on production servers as they may break your already live applications.

The following are some of the updates introduced in version 7.3 that greatly improve the performance of PHP 7.3 compared to previous versions.

  • Flexible Heredoc and Nowdoc syntax
  • Allow trailing commas in function calls
  • JSON_THROW_ON_ERROR
  • PCRE2 migration
  • list( ) Allocation Reference
  • is_countable Function
  • array_key_first(), array_key_last()
  • Argon2 Password Hash Enhancement
  • Deprecated and Removed image2wbmp()
  • Deprecation and removal of case-insensitive constants
  • Same site cookies
  • FPM updates
  • Improved file deletion under Windows

Let’s discuss each of the above updates one by one.

Flexible Heredoc and Nowdoc syntax The

Heredoc and Nowdoc syntax can be of great help when working with long strings that span multiple lines. It requires that the end identifier should be the first string that appears on a new line.

// 除了这样:

$query = <<<SQL

SELECT *

FROM `table`

WHERE `column` = true;

SQL;

// 这样也可以:

$query = <<<SQL

   SELECT *

   FROM `table`

   WHERE `column` = true;

   SQL;
Copy after login

Overall, this update proposes two improvements, as follows:

  1. Indentation is supported before closing the identifier
  2. No more after closing the identifier Forced line breaks

In the above example, you can easily see these changes.

Tail commas are allowed in function calls

Append a trailing comma at the end of the parameter, element, and variable lists. Sometimes we need to pass a large number of elements in arrays and function calls (especially variable parameter functions). If a comma is missed, an error will be reported. In this case, the trailing comma is very useful. This feature is already allowed within arrays, and starting with PHP 7.2, the grouped namespace (Grouped Namespaces) syntax also supports trailing commas.

use Foo\Bar\{
   Foo,
   Bar,
};

$foo = [
   &#39;foo&#39;,
   &#39;bar&#39;,
];
Copy after login

The trailing comma is very useful when a new value needs to be appended here. This is especially true within variadic functions such as unset().

unset(
   $foo,
   $bar,
   $baz,
);
Copy after login

At the same time, when you use the compact() function to pass a batch of variables to the template engine, this is also an example that can be used.

echo $twig->render(
   'index.html',
   compact(
       'title',
       'body',
       'comments',
   )
);
Copy after login

In some cases where continuous or grouped data needs to be constructed, the array_merge() function is often used to merge arrays. You can also use a trailing comma:

$newArray = array_merge(
   $arrayOne,
   $arrayTwo,
   ['foo', 'bar'],
);
Copy after login

Likewise, you can use this feature when calling any method, function, or closure.

class Foo
{
 public function __construct(...$args) {
   //
 }

 public function bar(...$args) {
   //
 }

 public function __invoke(...$args) {
   //
 }
}

$foo = new Foo(
 'constructor',
 'bar',
);

$foo->bar(
 'method',
 'bar',
);

$foo(
 'invoke',
 'bar',
);
Copy after login

JSON_THROW_ON_ERROR

To parse JSON response data, there are two functions json_encode() and json_decode() available. Unfortunately, none of them have proper error throwing behavior. json_encode will only return false when it fails; json_decode will return null when it fails, and null can be used as Legal JSON value. The only way to get an error is to call json_last_error() or json_last_error_msg(), which will return machine-readable and human-readable global error status respectively.

The solution proposed by this RFC is to add a new JSON_THROW_ON_ERROR constant to the JSON function to ignore the global error status. When an error occurs, the JSON function will throw a JsonException exception. The exception message (message) is the return value of json_last_error(), and the exception code (code) is the return value of json_last_error_msg(). The following is a calling example:

json_encode($data, JSON_THROW_ON_ERROR);

json_decode("invalid json", null, 512, JSON_THROW_ON_ERROR);

// 抛出 JsonException 异常
Copy after login

Upgrade PCRE2

PHP uses PCRE as the regular expression engine. But starting from PHP 7.3, PCRE2 will show its talents as a new regular engine. Therefore, you need to migrate existing regular expressions to comply with PCRE2 rules. These rules are more intrusive than before. Please see the following example:

preg_match('/[\w-.]+/', '');
Copy after login

This expression will fail to match in the new version of PHP and will not trigger a warning. Because PCRE2 is now strict, hyphens (-) must be moved to the end or escaped if they are to be matched instead of being used to represent a range.

After updating to PCRE2 10.x, the following and more features are supported:

  • 相对后向引用 \g{+2}(等效于已存在的 \g{-2}
  • PCRE2 版本检查 (?(VERSION>=x)...)
  • (*NOTEMPTY)(*NOTEMPTY_ATSTART) 告知引擎勿返回空匹配
  • (*NO_JIT) 禁用 JIT 优化
  • (*LIMIT_HEAP=d) 限制堆大小为 d KB
  • (*LIMIT_DEPTH=d) 设置回溯深度限制为 d
  • (*LIMIT_MATCH=d) 设置匹配数量限制为 d

译者注:国内正则术语参差不一,「后向引用」—— Back References,又称「反向引用」、「回溯引用」等,此处参考 PHP 官方手册的中文译本。

list() 赋值引用

PHP 中的 list() 现在可以赋值给引用,在当前版本中 list() 中赋值不能使用引用,在 PHP 7.3 中将允许使用引用,新改进的语法如下:

$array = [1, 2];
list($a, &$b) = $array;
Copy after login

相当于

$array = [1, 2];
$a = $array[0];
$b =& $array[1];
Copy after login

在 PHP 7.3 的变更中,我们还可以与 foreach() 方法一起嵌套使用

$array = [[1, 2], [3, 4]];
foreach ($array as list(&$a, $b)) {
   $a = 7;
}
var_dump($array);
Copy after login

is_countable 函数

在 PHP 7.2 中,用 count() 获取对象和数组的数量。如果对象不可数,PHP 会抛出警告⚠️ 。所以需要检查对象或者数组是否可数。 PHP 7.3 提供新的函数 is_countable() 来解决这个问题。

该 RFC 提供新的函数 is_countable(),对数组类型或者实现了 Countable 接口的实例的变量返回 true 。

之前:

if (is_array($foo) || $foo instanceof Countable) {
   // $foo 是可数的
}
Copy after login

之后:

if (is_countable($foo)) {
   // $foo 是可数的
}
Copy after login

array_key_first(), array_key_last()

当前版本的 PHP 允许使用 reset()end()key() 等方法,通过改变数组的内部指针来获取数组首尾的键和值。现在,为了避免这种内部干扰,PHP 7.3 推出了新的函数来解决这个问题:

  • $key = array_key_first($array); 获取数组第一个元素的键名
  • $key = array_key_last($array); 获取数组最后一个元素的键名

让我们看一个例子:

// 关联数组的用法
$array = ['a' => 1, 'b' => 2, 'c' => 3];

$firstKey = array_key_first($array);
$lastKey = array_key_last($array);

assert($firstKey === 'a');
assert($lastKey === 'c');

// 索引数组的用法
$array = [1 => 'a', 2 => 'b', 3 => 'c'];

$firstKey = array_key_first($array);
$lastKey = array_key_last($array);

assert($firstKey === 1);
assert($lastKey === 3);
Copy after login

译者注:array_value_first()array_value_last() 并没有通过 RFC 表决;因此 PHP 7.3 内仅提供了 array_key_first() 以及 array_key_last() 函数。
参考链接:https://wiki.php.net/rfc/array_key_first_l...

Argon2 和 Hash 密码加密性能增强

在PHP的早期版本中,我们增加了Argon2和哈希密码加密算法,这是一种使用哈希加密算法来保护密码的现代算法。它有三种不同的类型,Argon2i,Argon2d和Argon 2id。 我们针对Argon2i密码散列和基于密码的密钥生成进行了优化。 Argon2d性能更快,并使用依赖于内存的数据访问。 Argon2i使用与内存无关的数据访问。 Argon2id是Argon2i和Argon2d的混合体,使用依赖于数据和与数据独立的存储器访问的组合。

password_hash():

Argon2id现在是在paswword_ *函数中使用的推荐的Argon2变量。

具有自定义成员方法的名称的Argon2id与PASSWORD_ARGON2I的使用方法相同
password_hash('password',PASSWORD_ARGON2ID,['memory_cost'=> 1 << 17,&#39;time_cost&#39;=> 4,'threads'=> 2]);
Copy after login

password_verify();

除了Argon2i之外,password_verify()函数也适用于Argon2id。

password_needs_rehash();

此函数也将接受Argon2id哈希值,如果任何变量成员发生变化,则返回true。

$hash = password_hash('password', PASSWORD_ARGON2ID);
password_needs_rehash($hash, PASSWORD_ARGON2ID); // 返回假
password_needs_rehash($hash, PASSWORD_ARGON2ID, ['memory_cost' => 1<<17]); // 返回真
Copy after login

废弃并移除 image2wbmp()

该函数能够将图像输出为 WBMP 格式。另一个名为 imagewbmp() 的函数也同样具备单色转换的作用。因此,出于重复原因,image2wbmp() 现已被废弃,你可使用 imagewbmp() 代替它。此函数被弃用后,再次调用它将会触发已弃用警告。待后续此函数被移除后,再次调用它将会触发致命错误。

废弃并移除大小写不敏感的常量

使用先前版本的 PHP,你可以同时使用大小写敏感和大小写不敏感的常量。但大小写不敏感的常量会在使用中造成一点麻烦。所以,为了解决这个问题,PHP 7.3 废弃了大小写不敏感的常量。

原先的情况是:

  • 类常量始终为「大小写敏感」。
  • 使用 const 关键字定义的全局常量始终为「大小写敏感」。注意此处仅仅是常量自身的名称,不包含命名空间名的部分,PHP 的命名空间始终为「大小写不敏感」。
  • 使用 define() 函数定义的常量默认为「大小写敏感」。
  • 使用 define() 函数并将第三个参数设为 true 定义的常量为「大小写不敏感」。

如今 PHP 7.3 提议废弃并移除以下用法:

  • In PHP 7.3: 废弃使用 true 作为 define() 的第三个参数。
  • In PHP 7.3: 废弃使用与定义时的大小写不一致的名称,访问大小写不敏感的常量。truefalse 以及 null 除外。

同站点 Cookie

PHP 7.3 在建议在使用 cookies 时,增加同站点标志。这个 RFC 会影响4个系统函数。

  1. setcookie
  2. setrawcookie
  3. session_set_cookie_params
  4. session_get_cookie_params

这个影响会在两种情况下起作用。其中一种方式会添加函数的新参数
,另一种方式允许以数组形式的选项代替其他单独选项。

bool setcookie(

   string $name

   [, string $value = ""

   [, int $expire = 0

   [, string $path = ""

   [, string $domain = ""

   [, bool $secure = false

   [, bool $httponly = false ]]]]]]

)

bool setcookie (

   string $name

   [, string $value = ""

   [, int $expire = 0

   [, array $options ]]]

)

// 两种方式均可.
Copy after login

FPM 更新

FastCGI 进程管理器也进行了更新,现在提供了新的方式来记录 FPM 日志。

log_limit: 设置允许的日志长度,可以超过 1024 字符。

log_buffering: 允许不需要额外缓冲去操作日志。

decorate _workers_output: 当启用了 catch_workers_output 时,系统会去禁用渲染输出。

改进 Windows 下的文件删除

官方文档所述:

默认情况下,文件描述符以共享读、写、删除的方式去操作。 这很有效的去映射 POSIX 并允许去删除正在使用中的文件。但这并不是100%都是一样的,不同的平台可能仍存在一些差异。删除操作之后,文件目录仍存在直到所有的文件操作被关闭。

结束语

之前我们已经讲解了最新版本的 PHP7.3 的特点,包含了许多新增跟弃用的功能。这些功能都可以在 php.net 网站上找到,并且已经合并到主分支上了。你现在就可以使用这些新功能部署在自己的服务器上,你也可以打开官方RFC页面查阅每一个详细版本。如果你对着新版 PHP7.3 有任何问题,你可以在评论下写下自己的想法。

相关PHP视频教程推荐:《PHP视频教程》

The above is the detailed content of An article to help you understand the PHP 7.3 update. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!