Abstract Syntax Tree/Uniform Variable Syntax In PHP 7+

Abstract Syntax Tree/Uniform Variable Syntax In PHP 7+

On my previous post (PHP 7 In-depth Look), I discussed in-depth about the features of PHP 7 (you can read it here if you have not). In this post, I am going to be talking about The Abstract Syntax Tree(AST)/Uniform Variable Syntax in PHP 7+.

PHP 7 introduced a new layer which is called the Abstract Syntax Tree(AST) which helps in decoupling the process of parsing from the pseudo-compile process. Note that this new layer does not have much impact on performance but it make the syntax uniform. Uniform variable syntax/abstract syntax tree aims to establish internally consistent variable syntax, references are accessed from left to right instead of right to left.

Dereferencing

One of the major benefits of AST is Dereferencing. This makes it possible to either acquire or run a property from a method of an object, immediately access an array element and execute a callback immediately. So what changed in PHP 5 and PHP 7? In PHP 5, support for such was not complete and inconsistent, to do such in PHP 5, you need to assign the callback or anonymous function to a variable and then execute it but in PHP 7 you can execute it immediately. By appending (), the anonymous function is immediately executed (check the first example below). Looks familiar? Yes, this has been possible in JavaScript if you are familiar with JS. This kind of function is called an IIFE(Immediately-invoked function expression).
The following expressions are allowed in PHP 7+: (..)(), (..)[‘property’], (…)->property, (…)->method(), (…)::$property, (…)::method().

Why use an IIFE?

It does not expose your variables or objects inside an IIFE to the global scope. In other words, it protects the anonymous function local scope from the environment in which it is placed (the global scope). Note that you cannot access a property or method inside an IIFE that is outside the scope of the IIFE.

Show me SOME codes!

In the example above, we created an anonymous function and executed it immediately.

In the example above, we created an anonymous class and executed it immediately.

The statement $drinks()['Coke']();  is parsed left-to-right as follows:

  • $drinks() is executed which returns an array.
  • [‘Coke’] dereferences array element ‘Coke’, which returns a callback
  • () executes this callback, which prints out “Best drink ever”


The following are also possible in which the result of a method call can be called again directly:

  • method()()
  • $obj->method()()
  • ClassA::metho()()
  • $closure()()

Thanks for reading. If you like this post, please feel free to recommend this to other people. kindly share this or share your thoughts in the comment section below.

Cheers.

References and further reading
https://wiki.php.net/rfc/abstract_syntax_tree

 

SHARE ON