Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically generate parameter assignations in class constructors in PhpStorm?

Tags:

php

phpstorm

Does anyone know how to save typing in PhpStorm when you create a class constructor and you want to assign all the parameters to the respective class fields? I write it by hand now and I can do it quite quickly with the autocomplete feature, yet it is still a very tedious process.

For example:

class Foo
{
    private $param1; 
    private $param2;
    private $param3;    

    public function __construct($param1, $param2, $param3) {
          // Can I somehow automatically generate the following lines:
          //
          // $this->param1 = $param1;
          // $this->param2 = $param2;
          // $this->param3 = $param3;
          //
          //?
    }      
}
like image 842
Martin Vseticka Avatar asked Dec 15 '14 15:12

Martin Vseticka


3 Answers

Use "Initialize fields" intention. For that: place caret on one of the parameters and invoke QuickFix menu (Alt + Enter or by clicking on light bulb icon).

enter image description here

like image 61
LazyOne Avatar answered Nov 07 '22 20:11

LazyOne


In case you want to have PhpStorm generate the constructor too you can go to Code -> Generate -> Constructor. This will take care of inserting the parameters you want as well as their initialization.

Or press Alt+Insert and choose Constructor...

like image 25
DGS Avatar answered Nov 07 '22 20:11

DGS


If you move the cursor to the word '__constructor', within a second or two a lightbulb pops up. when you press it you get an option "Initialize properties". If you select that option a popup appears where you can specify for which argument you want to create and assign a property.

[Lightbulb[1]]Argument popup

like image 4
Erlend ter Maat Avatar answered Nov 07 '22 20:11

Erlend ter Maat