search
HomeBackend DevelopmentPHP TutorialAn article to help you understand the PHP 7.3 update

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 = <p> Overall, this update proposes two improvements, as follows: </p><ol>
<li> Indentation is supported before closing the identifier </li>
<li> No more after closing the identifier Forced line breaks</li>
</ol><p>In the above example, you can easily see these changes. </p><h2 id="Tail-commas-are-allowed-in-function-calls">Tail commas are allowed in function calls</h2><p>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 (<code>Grouped Namespaces</code>) syntax also supports trailing commas. </p><pre class="brush:php;toolbar:false">use Foo\Bar\{
   Foo,
   Bar,
};

$foo = [
   'foo',
   'bar',
];

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,
);

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',
   )
);

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'],
);

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',
);

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 异常

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-.]+/', '');

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;

相当于

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

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

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

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 是可数的
}

之后:

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

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);

译者注: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  4,'threads'=> 2]);

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<h2 id="废弃并移除-image-wbmp">废弃并移除 image2wbmp()</h2><p>该函数能够将图像输出为 WBMP 格式。另一个名为 <code>imagewbmp()</code> 的函数也同样具备单色转换的作用。因此,出于重复原因,<a href="https://wiki.php.net/rfc/image2wbmp">image2wbmp()</a> 现已被废弃,你可使用 <code>imagewbmp()</code> 代替它。此函数被弃用后,再次调用它将会触发已弃用警告。待后续此函数被移除后,再次调用它将会触发致命错误。</p><h2 id="废弃并移除大小写不敏感的常量">废弃并移除大小写不敏感的常量</h2><p>使用先前版本的 PHP,你可以同时使用大小写敏感和大小写不敏感的常量。但大小写不敏感的常量会在使用中造成一点麻烦。所以,为了解决这个问题,PHP 7.3 废弃了大小写不敏感的常量。</p><p>原先的情况是:</p>
  • 类常量始终为「大小写敏感」。
  • 使用 const 关键字定义的全局常量始终为「大小写敏感」。注意此处仅仅是常量自身的名称,不包含命名空间名的部分,PHP 的命名空间始终为「大小写不敏感」。
  • 使用 define() 函数定义的常量默认为「大小写敏感」。
  • 使用 define() 函数并将第三个参数设为 true 定义的常量为「大小写不敏感」。

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

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

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

)

// 两种方式均可.

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!

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment