search
HomeBackend DevelopmentPHP TutorialChanges brought about by PHP7's Abstract Syntax Tree (AST)

Changes brought about by PHP7's Abstract Syntax Tree (AST)

What is an abstract syntax tree?

Abstract syntax tree (AST) is a tree representation of the abstract syntax structure of the source code. Each node on the tree represents a structure in the source code. This is why It is abstract because the abstract syntax tree does not represent every detail of the real grammar. For example, nested brackets are implicit in the structure of the tree and are not presented in the form of nodes. The abstract syntax tree does not depend on the grammar of the source language, which means that the context-free grammar used in the syntax analysis stage [Grammar is the formal rules used to describe the grammatical structure of a language. Any language has its own grammar, whether it is machine language or natural language. 】, because when writing grammar, equivalent transformations are often performed on the grammar (elimination of left recursion, backtracking, ambiguity, etc.), which will introduce some redundant components into the grammar analysis, adversely affect the subsequent stages, and even Make the whole stage confusing. For this reason, many compilers often need to construct syntax analysis trees independently to establish a clear interface for the front end and back end

PHP-Parser’s project homepage is https://github.com/nikic/PHP- Parser. It can perfectly parse multiple versions of PHP and generate an abstract syntax tree.

New execution process

An important change in the core of PHP7 is the addition of AST. In PHP5, the execution process from php scripts to opcodes is:

1.Lexing: lexical scanning analysis, converting source files into token streams;

2.Parsing: syntax analysis, Op arrays are generated at this stage.

In PHP7, op arrays are no longer directly generated during the syntax analysis phase, but AST is generated first, so there is one more step in the process:

1.Lexing: lexical scanning analysis, converting the source file into token stream;

2.Parsing: syntax analysis, generating abstract syntax tree from token stream;

3.Compilation: generating op arrays from abstract syntax tree.

Execution time and memory consumption

From the above steps, this is one more step than the previous process, so according to common sense, this will increase the program execution time and memory usage. But in fact, the memory usage has indeed increased, but the execution time has decreased.

The following results are obtained by testing three scripts: small (about 100 lines of code), medium (about 700 lines), and large (about 2800 lines). Test script: https://gist.github .com/nikic/289b0c7538b46c2220bc.

Execution time of compiling each file 100 times (note that the test results of the article are from 14 years, when PHP7 was still called PHP-NG):

Changes brought about by PHP7s Abstract Syntax Tree (AST)

Memory peak value in a single compilation:

Changes brought about by PHP7s Abstract Syntax Tree (AST)

The test results of a single compilation may not represent actual usage. The following is using PhpParser The results of the complete project test:

Changes brought about by PHP7s Abstract Syntax Tree (AST)

The test shows that after using AST, the overall execution time of the program is improved by about 10% to 15%, but the memory consumption is also increased. , the increase is obvious in a single compilation of large files, but it is not a serious problem during the entire project execution.

Also note that the above results are all without Opcache. When Opcache is turned on in a production environment, the increase in memory consumption is not a big problem.

Semantic changes

If it is just a time optimization, it does not seem to be a sufficient reason to use AST. In fact, the implementation of AST is not based on time optimization considerations, but to solve syntax problems. Let’s take a look at some changes in semantics.

yield does not require parentheses

In the PHP5 implementation, if you use yield in an expression context (such as on the right side of an assignment expression), you You must use parentheses on both sides of the yield declaration:

<?php
$result = yield fn();   // 不合法的
$result = (yield fn()); // 合法的

This behavior is only due to the implementation limitations of PHP5. In PHP7, parentheses are no longer necessary. Therefore, the following writing methods are also legal:

<?php
$result = yield;
$result = yield $v;
$result = yield $k => $v;

Of course, you must follow the application scenarios of yield.

Brackets do not affect behavior

In PHP5,

<?php
($foo)[&#39;bar&#39;] = &#39;baz&#39;;
# PHP Parse error: Syntax error, unexpected &#39;[&#39; on line 1

But in PHP7, the two writing methods mean the same thing.

Similarly, if the parameters of the function are wrapped in parentheses, there is a problem with type checking. This problem has also been solved in PHP7:

<?php
function func() {
    return [];
}

function byRef(array &$a) {
}

byRef((func()));

The above code will not alarm in PHP5 unless byRef is used (func()), but in PHP7, the following error will occur regardless of whether there are parentheses on both sides of func():

PHP Strict standards:  Only variables should be passed by reference ...

Changes in list()

list 关键字的行为改变了很多。list 给变量赋值的顺序(等号左右同时的顺序)以前是从右至左,现在是从左到右:

<?php
list($array[], $array[], $array[]) = [1, 2, 3];
var_dump($array);
// PHP5: $array = [3, 2, 1]
// PHP7: $array = [1, 2, 3]
# 注意这里的左右的顺序指的是等号左右同时的顺序,
# list($a, $b) = [1, 2] 这种使用中 $a == 1, $b == 2 是没有疑问的。

产生上面变化的原因正是因为在 PHP5 的赋值过程中,3 会最先被填入数组,1 最后,但是现在顺序改变了。

同样的变化还有:

<?php
$a = [1, 2];
list($a, $b) = $a;
// PHP5: $a = 1, $b = 2
// PHP7: $a = 1, $b = null + "Undefined index 1"

这是因为在以前的赋值过程中 $b 先得到 2,然后 $a 的值才变成1,但是现在 $a 先变成了 1,不再是数组,所以 $b 就成了null。

list 现在只会访问每个偏移量一次

<?php
list(list($a, $b)) = $array;
// PHP5:
$b = $array[0][1];
$a = $array[0][0];
// PHP7:
// 会产生一个中间变量,得到 $array[0] 的值
$_tmp = $array[0];
$a = $_tmp[0];
$b = $_tmp[1];

空的 list 成员现在是全部禁止的,以前只是在某些情况下:

<?php
list() = $a;           // 不合法
list($b, list()) = $a; // 不合法
foreach ($a as list()) // 不合法 (PHP5 中也不合法)

引用赋值的顺序

引用赋值的顺序在 PHP5 中是从右到左的,现在时从左到右:

<?php
$obj = new stdClass;
$obj->a = &$obj->b;
$obj->b = 1;
var_dump($obj);
// PHP5:
object(stdClass)#1 (2) {
 ["b"] => &int(1)
  ["a"] => &int(1)
}
// PHP7:
object(stdClass)#1 (2) {
 ["a"] => &int(1)
  ["b"] => &int(1)
}

__clone 方法可以直接调用

现在可以直接使用 $obj->__clone() 的写法去调用 __clone 方法。 __clone 是之前唯一一个被禁止直接调用的魔术方法,之前你会得到一个这样的错误:

Fatal error:Cannot call __clone() method on objects -use &#39;clone $obj&#39; instead in...

变量语法一致性

AST 也解决了一些语法一致性的问题,这些问题是在另外一个 RFC 中被提出的:https://wiki.php.net/rfc/uniform_variable_syntax.

在新的实现上,以前的一些语法表达的含义和现在有些不同,具体的可以参照下面的表格:

Changes brought about by PHP7s Abstract Syntax Tree (AST)

整体上还是以前的顺序是从右到左,现在从左到右,同时也遵循括号不影响行为的原则。这些复杂的变量写法是在实际开发中需要注意的。

相关推荐:《PHP教程

The above is the detailed content of Changes brought about by PHP7's Abstract Syntax Tree (AST). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:uckendo. If there is any infringement, please contact admin@php.cn delete
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.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft