- URL: https://www.laruence.com/en/2011/11/11/2296.html
- Please include attribution when republishing.
In earlier PHP, we could not directly operate on the result of instantiating an object:
<?php (new Foo())->show(); //PHP Parse error: syntax error, unexpected T_OBJECT_OPERATOR
We could only store the instance first, then call it:
$a = new Foo(); $a->show();
Many people have requested this improvement, but due to an implementation issue it was never added to PHP.
Let me explain: PHP's syntax parsing system is a long-standing one. Over its rather long history of continuous patching, it has, more or less, ended up with some particular characteristics. And a full rewrite would be both time-consuming and laborious, and would be hard to make fully compatible with the current state. So I think a complete rewrite can only happen in PHP 6 (on behalf of the dev group, I'll announce that PHP 6 development has already been stopped, and this kind of talk is not on the table for now either).
And if we take the patching approach, it introduces an unresolvable shift/reduce conflict. I previously tried to implement this feature, but hit this problem, so I didn't submit it..
However, as demand for this feature grew, gradually everyone felt that even one more shift/reduce conflict... well, it's not a big deal. Hehe, so:
Now, this feature is finally supported, thanks to Felipe's work (Instance and method call/property access). We can now write syntax like:
<?php (new foo())->bar() (new $foo())->bar (new $bar->y)->x (new foo)[0]
You may have noticed that all the instantiation expressions need to be wrapped in parentheses. Yes, if we don't do that, first, there would be an ambiguous syntax like:
new $bar->y->x;
In this case, there would be a contradiction: is it (new $bar)->y, or (new $bar->y)->x.
Another reason is that, in PHP's current grammar system, if we adopted the no-parentheses approach, it would introduce even more shift/reduce conflicts.
But I believe the parentheses are no big deal — at least it looks clearer.
Speaking of which, a tangent: I'm curious — how many known unresolvable "shift/reduce" conflicts must C++'s syntax parsing have? Anyone who knows? Hehe. (Postscript: gcc stopped using lex/yacc starting from 3.0, but from the gcc-2.95.1 source code, we can see that gcc's known unresolvable shift/reduce conflicts are: 51 (%expect 51 in gcc-2.95.1/gcc/c-parse.y), hehe)
Currently, 5.4RC1 has been released. Those interested can try it early and help test PHP 🙂 PHP 5.4RC1, enjoy!
That said, a reminder: PHP 5.4 is still under development. Before the final release, any new feature may be adjusted or changed. If you have any suggestions, feedback is welcome, to help make PHP even better.
Thanks
For more updates, follow: Changelog
Be First to Comment