Parse arbitrary expressions
sergio-fferreira opened this issue · comments
Hello, let's assume I want to construct a variable named "myName" with an arbitrary expression in the right side ($myName = {expr}
). The expression is only known at runtime.
Is there any function similar to parseExpr(string $expr)
that receives a string of raw code, for example "1 + func(2)"
and returns the node structure associated with it? As far as I know, the regular parse()
needs at least complete statements to work.
In this way, it could be possible to use:
$expr = '1 + func(2)';
return new Stmt\Expression(new Expr\Assign($varName, parseExpr($expr)));
Alternatively, would it be possible to build a custom node that represents raw code, which would be printed directly using PrettyPrinter
?
Thank you in advance!
The way to do this would be to create the string <?php {expr};
, call parse()
and then take $stmts[0]->expr
.
Thank you! Indeed, it does work for expressions.
Maybe slightly offtopic, but in my project I have to receive excerpts of code at runtime, to replace a given node. They can be expressions or not.
Is there any way to simply replace a Node
with raw code? Maybe creating a custom Node
that stores the code and extending the PrettyPrint
class?
Again, thank you for your support!
Is there any way to simply replace a Node with raw code? Maybe creating a custom Node that stores the code and extending the PrettyPrint class?
Doing what you said should work.
Thank you!