The Extract Field refactoring lets you declare a new field and initialize it with the selected expression. The original expression is replaced with the usage of the field.
Place the cursor within a piece of code you want to extract into a field.
Press Ctrl+Alt+F or on the main menu, select.
Select an expression you want introduce as a field. If PhpStorm detects more than one occurrence in your code, it lets you specify which occurrences to replace.
- Provide the name of the new field and choose where it will be initialized: in its declaration, in the current method, or in the class constructor.
Extracting a field using the dialog box
In the editor, select the expression or variable to be replaced with a field, or just place the cursor within such an expression or variable declaration.
In the main menu, or the context menu of the selection, choose, or press Ctrl+Alt+F.
In the Extract Field Dialog dialog that opens:
Specify the name of the field.
Specify where the new field should be initialized by selecting the necessary option under Initialize in.
In the Visibility area, select the visibility scope for the new field.
To replace all the occurrences of the selected expression (if the selected expression is found more than once in the class), select the Replace all occurrences checkbox.
Let's extract the
'param_query' argument into a
$query class field. As a result, PhpStorm declares the new
public $query field and changes all
'param_query' occurrences to
self::$query. The resulting code will look as follows depending on where you've chosen to initialize the field: