PhpStorm 2018.2 Help

Generating Code

PhpStorm provides multiple ways to generate common code constructs and recurring elements, which helps you increase productivity. These can be either predefined or custom templates, which are applied differently based on the context, various wrappers and automatic pairing of characters. Additionally, PhpStorm provides code completion and Emmet support.

Generate constructors

PhpStorm can generate a constructor that initializes specific class fields using values of corresponding arguments.

To generate a constructor for a class:

  1. On the Code menu, click Generate.

  2. In the Generate popup, click Constructor.

  3. 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:

class MyClass { public $field; /** * MyClass constructor. * @param $field */ public function __construct($field) { $this->field = $field; } }

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 file template. By default, as specified in these templates, setters are generated with the set prefix, and getters with the get or is prefix according to the inferred field type boolean or con-boolean. The prefix is the value of the ${GET_OR_IS} variable in the default getter template. The default template is configured in the Code tab on the File and Code Templates.

To generate getters and setters for a class:

  1. On the Code menu, click Generate.

  2. In the Generate popup, click one of the following:
    • Getter to generate accessor methods for getting the current values of class fields.

    • Setter to generate mutator methods for setting the values of class fields.

    • Getter and Setter to generate both accessor and mutator methods.

  3. Select the fields to generate getters or setters for and click OK.

The following code fragment shows the result of generating the getter and setter methods for a class with one field var:

class MyClass { /** * @return mixed */ public function getVar() { return $this->var; } /** * @param mixed $var */ public function setVar($var): void { $this->var = $var; } public $var; }
Last modified: 2 November 2018