Generate code
PhpStorm provides multiple ways to generate common code constructs and recurring elements, which helps you increase productivity. These can be either file templates used when creating a new file, custom or predefined live templates that are applied differently based on the context, various wrappers, or automatic pairing of characters.
Additionally, PhpStorm provides code completion and Emmet support.
Generate constructors
PhpStorm can generate a constructor that initializes specific class properties using values of corresponding arguments.
Generate a constructor for a class
On the Code menu, click Generate Alt+Insert.
In the Generate popup, click Constructor.
If the class contains fields, select the fields to be initialized by the constructor and click OK.
The following code fragment shows the result of generating a constructor for a class:
Generate getters and setters
PhpStorm can generate accessor and mutator methods (getters and setters) for the fields in your classes. Generated methods have only one argument.
In the PHP context, getters and setters are generated using the PHP Getter/Setter/Fluent setter file templates. By default, as specified in these templates, setters are generated with the set
prefix, and getters with the is
or get
prefix according to the inferred property type – boolean
or non-boolean
. The prefix is the value of the ${GET_OR_IS}
variable in the default getter template. The templates are configured in the Code tab on the File and Code Templates.
On the Code menu, click Generate Alt+Insert.
In the Generate popup, click one of the following:
Getter to generate accessor methods for getting the current values of class properties.
Setter to generate mutator methods for setting the values of class properties.
Getter and Setter to generate both accessor and mutator methods.
In the Choose Properties dialog, select the fields for which you want to generate getters and setters, and specify the code generation configuration.
Fluent setters: unselect the checkbox to skip creating a fluent setter, which additionally returns a
$this
reference to the current class. Consider the following example:class Example { public $foo; public function set_foo($foo): void { $this->foo = $foo; } }class Example { public $foo; public function set_foo($foo) { $this->foo = $foo; return $this; } }Add PHPDoc: unselect the checkbox to skip adding an auto-generated PHPDoc block to the code snippet. To change the scope of generated PHPDoc tags, use the radio buttons.
Configure: click to configure the order and naming scheme of the generated getters and setters.
The following code fragment shows the result of generating the getter and setter methods for a class with one field var
: