Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

php-generator

> 编程语言
Open source

Generates neat PHP code for you. Supports new PHP 8.5 features.

2.3K stars0 likes3 views
WebsiteGitHub

About

Generates neat PHP code for you. Supports new PHP 8.5 features.

 

Are you looking for a tool to generate PHP code for classes, functions, or complete PHP files?

✅ Supports all the latest PHP features like property hooks, enums, attributes, etc.
✅ Allows you to easily modify existing classes
✅ Output compliant with PSR-12 / PER coding style
✅ Highly mature, stable, and widely used library

 

Installation

Download and install the library using the Composer tool:

bash
composer require nette/php-generator

PhpGenerator 4.2 is compatible with PHP 8.1 to 8.5. Documentation can be found on the library's website.

 

Support Me

Do you like PHP Generator? Are you looking forward to the new features? Thank you!

 

Classes

Let's start with an example of creating a class using ClassType:

php
$class = new Nette\PhpGenerator\ClassType('Demo');

$class
	->setFinal()
	->setExtends(ParentClass::class)
	->addImplement(Countable::class)
	->addComment("Class description.\nSecond line\n")
	->addComment('@property-read Nette\Forms\Form $form');

// generate code simply by typecasting to string or using echo:
echo $class;

This will return:

php
/**
 * Class description
 * Second line
 *
 * @property-read Nette\Forms\Form $form
 */
final class Demo extends ParentClass implements Countable
{
}

To generate the code, you can also use a so-called printer, which, unlike echo $class, can be further configured:

php
$printer = new Nette\PhpGenerator\Printer;
echo $printer->printClass($class);

You can add constants (class Constant) and properties (class Property):

php
$class->addConstant('ID', 123)
	->setProtected() // constant visibility
	->setType('int')
	->setFinal();

$class->addProperty('items', [1, 2, 3])
	->setPrivate() // or setVisibility('private')
	->setStatic()
	->addComment('@var int[]');

$class->addProperty('list')
	->setType('?array')
	->setInitialized(); // outputs '= null'

This will generate:

php
final protected const int ID = 123;

/** @var int[] */
private static $items = [1, 2, 3];

public ?array $list = null;

And you can add methods:

php
$method = $class->addMethod('count')
	->addComment('Count it.')
	->setFinal()
	->setProtected()
	->setReturnType('?int') // return types for methods
	->setBody('return count($items ?: $this->items);');

$method->addParameter('items', []) // $items = []
	->setReference()           // &$items = []
	->setType('array');        // array &$items = []

The result is:

php
/**
 * Count it.
 */
final protected function count(array &$items = []): ?int
{
	return count($items ?: $this->items);
}

Promoted parameters introduced in PHP 8.0 can be passed to the constructor:

php
$method = $class->addMethod('__construct');
$method->addPromotedParameter('name');
$method->addPromotedParameter('args', [])
	->setPrivate();

The result is:

php
public function __construct(
	public $name,
	private $args = [],
) {
}

Readonly properties and classes be marked using the setReadOnly() function.


If an added property, constant, method, or parameter already exists, an exception is thrown.

Class members can be removed using removeProperty(), removeConstant(), removeMethod(), or removeParameter().

You can also add existing Method, Property, or Constant objects to the class:

php
$method = new Nette\PhpGenerator\Method('getHandle');
$property = new Nette\PhpGenerator\Property('handle');
$const = new Nette\PhpGenerator\Constant('ROLE');

$class = (new Nette\PhpGenerator\ClassType('Demo'))
	->addMember($method)
	->addMember($property)
	->addMember($const);

You can also clone existing methods, properties, and constants under a different name using cloneWithName():

php
$methodCount = $class->getMethod('count');
$methodRecount = $methodCount->cloneWithName('recount');
$class->addMember($methodRecount);

 

Interfaces or Traits

You can create interfaces and traits (classes InterfaceType and TraitType):

php
$interface = new Nette\PhpGenerator\InterfaceType('MyInterface');
$trait = new Nette\PhpGenerator\TraitType('MyTrait');

Using a trait:

php
$class = new Nette\PhpGenerator\ClassType('Demo');
$class->addTrait('SmartObject');
$class->addTrait('MyTrait')
	->addResolution('sayHello as protected')
	->addComment('@use MyTrait<Foo>');
echo $class;

The result is:

php
class Demo
{
	use SmartObject;
	/** @use MyTrait<Foo> */
	use MyTrait {
		sayHello as protected;
	}
}

 

Enums

You can easily create enums introduced in PHP 8.1 like this (class EnumType):

php
$enum = new Nette\PhpGenerator\EnumType('Suit');
$enum->addCase('Clubs');
$enum->addCase('Diamonds');
$enum->addCase('Hearts');
$enum->addCase('Spades');

echo $enum;

The result is:

php
enum Suit
{
	case Clubs;
	case Diamonds;
	case Hearts;
	case Spades;
}

You can also define scalar equivalents and create a "backed" enum:

php
$enum->addCase('Clubs', '♣');
$enum->addCase('Diamonds', '♦');

For each case, you can add a comment or attributes using addComment() or addAttribute().

 

Anonymous Classes

Pass null as the name, and you have an anonymous class:

php
$class = new Nette\PhpGenerator\ClassType(null);
$class->addMethod('__construct')
	->addParameter('foo');

echo '$obj = new class ($val) ' . $class . ';';

The result is:

php
$obj = new class ($val) {

	public function __construct($foo)
	{
	}
};

 

Global Functions

The code for functions is generated by the class GlobalFunction:

php
$function = new Nette\PhpGenerator\GlobalFunction('foo');
$function->setBody('return $a + $b;');
$function->addParameter('a');
$function->addParameter('b');
echo $function;

// or use the PsrPrinter for output compliant with PSR-2 / PSR-12 / PER
// echo (new Nette\PhpGenerator\PsrPrinter)->printFunction($function);

The result is:

php
function foo($a, $b)
{
	return $a + $b;
}

 

Anonymous Functions

The code for anonymous functions is generated by the class Closure:

php
$closure = new Nette\PhpGenerator\Closure;
$closure->setBody('return $a + $b;');
$closure->addParameter('a');
$closure->addParameter('b');
$closure->addUse('c')
	->setReference();
echo $closure;

// or use the PsrPrinter for output compliant with PSR-2 / PSR-12 / PER
// echo (new Nette\PhpGenerator\PsrPrinter)->printClosure($closure);

The result is:

php
function ($a, $b) use (&$c) {
	return $a + $b;
}

 

Short Arrow Functions

You can also output a short anonymous function using the printer:

php
$closure = new Nette\PhpGenerator\Closure;
$closure->setBody('$a + $b');
$closure->addParameter('a');
$closure->addParameter('b');

echo (new Nette\PhpGenerator\Printer)->printArrowFunction($closure);

The result is:

php
fn($a, $b) => $a + $b

 

Method and Function Signatures

Methods are represented by the class Method. You can set visibility, return value, add comments, attributes, etc.:

php
$method = $class->addMethod('count')
	->addComment('Count it.')
	->setFinal()
	->setProtected()
	->setReturnType('?int');

Individual parameters are represented by the class Parameter. Again, you can set all conceivable properties:

php
$method->addParameter('items', []) // $items = []
	->setReference()           // &$items = []
	->setType('array');        // array &$items = []

// function count(&$items = [])

To define the so-called variadics parameters (or also the splat, spread, ellipsis, unpacking or three dots operator), use setVariadic():

php
$method = $class->addMethod('count');
$method->setVariadic(true);
$method->addParameter('items');

This generates:

php
function count(...$items)
{
}

 

Method and Function Bodies

The body can be passed all at once to the setBody() method or gradually (line by line) by repeatedly calling addBody():

php
$function = new Nette\PhpGenerator\GlobalFunction('foo');
$function->addBody('$a = rand(10, 20);');
$function->addBody('return $a;');
echo $function;

The result is:

php
function foo()
{
	$a = rand(10, 20);
	return $a;
}

You can use special placeholders for easy variable insertion.

Simple placeholders ?

php
$str = 'any string';
$num = 3;
$function = new Nette\PhpGenerator\GlobalFunction('foo');
$function->addBody('return substr(?, ?);', [$str, $num]);
echo $function;

The result is:

php
function foo()
{
	return substr('any string', 3);
}

Placeholder for variadic ...?

php
$items = [1, 2, 3];
$function = new Nette\PhpGenerator\GlobalFunction('foo');
$function->setBody('myfunc(...?);', [$items]);
echo $function;

The result is:

php
function foo()
{
	myfunc(1, 2, 3);
}

You can also use named parameters for PHP 8 with ...?:

php
$items = ['foo' => 1, 'bar' => true];
$function->setBody('myfunc(...?:);', [$items]);

// myfunc(foo: 1, bar: true);

The placeholder is escaped with a backslash \?

php
$num = 3;
$function = new Nette\PhpGenerator\GlobalFunction('foo');
$function->addParameter('a');
$function->addBody('return $a \? 10 : ?;', [$num]);
echo $function;

The result is:

php
function foo($a)
{
	return $a ? 10 : 3;
}

 

Printer and PSR Compliance

The Printer class is used for generating PHP code:

php
$class = new Nette\PhpGenerator\ClassType('Demo');
// ...

$printer = new Nette\PhpGenerator\Printer;
echo $printer->printClass($class); // same as: echo $class

It can generate code for all other elements, offering methods like printFunction(), printNamespace(), etc.

There's also the PsrPrinter class, which outputs in accordance with PSR-2 / PSR-12 / PER coding style:

php
$printer = new Nette\PhpGenerator\PsrPrinter;
echo $printer->printClass($class);

Need custom behavior? Create your own version by inheriting the Printer class. You can reconfigure these variables:

…

How and why does the standard Printer differ from PsrPrinter? Why isn't there just one printer, the PsrPrinter, in the package?

The standard Printer formats the code as we do throughout Nette. Since Nette was established much earlier than PSR, and also because PSR took years to deliver standards on time, sometimes even several years after introducing a new feature in PHP, it resulted in a coding standard that differs in a few minor aspects. The major difference is the use of tabs instead of spaces. We know that by using tabs in our

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPcode-generatornettenette-frameworkphp

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言