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.
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.
$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:
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.
References and further reading