$methodRecount = $methodCount-> cloneWithName( 'recount') You can clone existing methods, properties and constants with a different name using cloneWithName(): $methodCount = $class-> getMethod( 'count') $class = ( new Nette\ PhpGenerator\ ClassType( 'Demo')) $const = new Nette\ PhpGenerator\ Constant( 'ROLE') $property = new Nette\ PhpGenerator\ Property( 'handle') You can also add existing Method, Property or Constant objects to the class: $method = new Nette\ PhpGenerator\ Method( 'getHandle') Members can be removed using removeProperty(), removeConstant(), removeMethod() or removeParameter(). If the added property, constant, method or parameter already exist, it will be overwritten. Readonly properties introduced by PHP 8.1 can be marked via setReadOnly(). It results in: public function _construct( $method-> addPromotedParameter( 'args', ) Promoted parameters introduced by PHP 8.0 can be passed to the constructor: $method = $class-> addMethod( '_construct') * int */ final protected function count( array & $items = ): ? int $method-> addParameter( 'items', ) // $items = > setBody( 'return count($items ?: $this->items) ') > setReturnNullable() // nullable return type > setReturnType( 'int') // method return type ** int */ private static $items = Īnd we can add methods with parameters: $method = $class-> addMethod( 'count')
It generates: final protected const ID = 123
> setPrivate() // or setVisibility('private') We can add constants ( Constant) and properties ( Property): $class-> addConstant( 'ID', 123) We can also use a printer to generate the code, which, unlike echo $class, we will be able to further configure: $printer = new Nette\ PhpGenerator\ Printer * Second line * * Nette\Forms\Form $form */ final class Demo extends ParentClass implements Countable It will render this result: /** * Description of class.
to generate PHP code simply cast to string or use echo: echo $class > addComment( "Description of class.\nSecond line\n") Let's start with a straightforward example of generating class using ClassType: $class = new Nette\ PhpGenerator\ ClassType( 'Demo') PhpGenerator 2.6 is compatible with PHP 5.6 to 7.3.PhpGenerator 3.0 is compatible with PHP 7.0 to 7.3.PhpGenerator 3.1 is compatible with PHP 7.1 to 7.3.PhpGenerator 3.2 – 3.5 is compatible with PHP 7.1 to 8.0.PhpGenerator 3.6 is compatible with PHP 7.2 to 8.1.PhpGenerator 4.0 is compatible with PHP 8.0 to 8.1.Thank you! Installation composer require nette/php-generator Support Meĭo you like PHP Generator? Are you looking forward to the new features? Do you need to generate PHP code of classes, functions, namespaces, etc.? This library with a friendly API will help you.ĭocumentation can be found on the website.