4 It is also possible to generate code using the parser, by first creating an Abstract Syntax Tree and then using the
5 pretty printer to convert it to PHP code. To simplify code generation, the project comes with builders which allow
6 creating node trees using a fluid interface, instead of instantiating all nodes manually. Builders are available for
7 the following syntactic elements:
9 * namespaces and use statements
10 * classes, interfaces and traits
11 * methods, functions and parameters
17 use PhpParser\BuilderFactory;
18 use PhpParser\PrettyPrinter;
21 $factory = new BuilderFactory;
22 $node = $factory->namespace('Name\Space')
23 ->addStmt($factory->use('Some\Other\Thingy')->as('SomeOtherClass'))
24 ->addStmt($factory->class('SomeClass')
25 ->extend('SomeOtherClass')
26 ->implement('A\Few', '\Interfaces')
27 ->makeAbstract() // ->makeFinal()
29 ->addStmt($factory->method('someMethod')
31 ->makeAbstract() // ->makeFinal()
32 ->setReturnType('bool')
33 ->addParam($factory->param('someParam')->setTypeHint('SomeClass'))
35 * This method does something.
37 * @param SomeClass And takes a parameter
41 ->addStmt($factory->method('anotherMethod')
42 ->makeProtected() // ->makePublic() [default], ->makePrivate()
43 ->addParam($factory->param('someParam')->setDefault('test'))
44 // it is possible to add manually created nodes
45 ->addStmt(new Node\Expr\Print_(new Node\Expr\Variable('someParam')))
48 // properties will be correctly reordered above the methods
49 ->addStmt($factory->property('someProperty')->makeProtected())
50 ->addStmt($factory->property('anotherProperty')->makePrivate()->setDefault(array(1, 2, 3)))
56 $stmts = array($node);
57 $prettyPrinter = new PrettyPrinter\Standard();
58 echo $prettyPrinter->prettyPrintFile($stmts);
61 This will produce the following output with the standard pretty printer:
68 use Some\Other\Thingy as SomeClass;
69 abstract class SomeClass extends SomeOtherClass implements A\Few, \Interfaces
71 protected $someProperty;
72 private $anotherProperty = array(1, 2, 3);
74 * This method does something.
76 * @param SomeClass And takes a parameter
78 public abstract function someMethod(SomeClass $someParam) : bool;
79 protected function anotherMethod($someParam = 'test')