Skip to content

Parse new with an expression and dynamic class constant fetch in php8 - #36

Merged
TomasVotruba merged 1 commit into
mainfrom
php8-new-expr-dynamic-class-const
Nov 23, 2026
Merged

TomasVotruba merged 1 commit into
mainfrom
php8-new-expr-dynamic-class-const

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

Two syntaxes the php8 grammar rejected, found by parsing every rector-src test fixture:

PHP Syntax Example
8.0 new with an arbitrary expression new ($prefix . 'Handler')($config), (new (static::getModel()))->newQuery()
8.3 dynamic class constant fetch Status::{$name}, $this::{'PREFIX_' . $name}

Both are common enough in real code (e.g. new (static::getModel()) in Laravel) that a downstream tool hitting one cannot process the file at all.

Grammar - mirrors zend_language_parser.y:

  • class_name_reference gains '(' expr ')', built as the existing ast.ExprBrackets
  • class_constant gains class_name :: '{' expr '}' and variable_class_name :: '{' expr '}'

AST - additive only:

  • ast.ExprClassConstFetch gains OpenCurlyBracketTkn and CloseCurlyBracketTkn, nil for a plain identifier name; same shape as ExprPropertyFetch for $object->{$name}
  • printer and dumper keep the tokens, formatter adds the braces when Const is not an identifier

The grammar conflict count is unchanged (3 shift/reduce, 7 reduce/reduce). php8.go regenerated with the latest goyacc - regenerating the unchanged grammar the same way reproduces the committed file byte for byte.

Tests: parse shape, print-back round trip (including spacing inside the brackets), formatter and printer. Verified downstream: reco's full test suite passes against this branch.

PHP 8.0 lets new take any parenthesized expression as the class,
new ($prefix . 'Handler')(), and PHP 8.3 lets the constant name of a class
constant fetch be computed, Foo::{$name}. Both were syntax errors.

The class of new (expr) is an ExprBrackets node. ExprClassConstFetch gains
OpenCurlyBracketTkn and CloseCurlyBracketTkn for the computed name, kept by
the printer and dumper and added by the formatter, the same way
ExprPropertyFetch handles $object->{$name}.
@TomasVotruba
TomasVotruba merged commit bd037f3 into main Nov 23, 2026
5 checks passed
@TomasVotruba
TomasVotruba deleted the php8-new-expr-dynamic-class-const branch November 23, 2026 12:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant