When the Extract Method refactoring is invoked, PhpStorm analyses the selected block of code and detects variables that are the input for the selected code fragment and the variables that are output for it.
The detected output variable is used as a return value for the extracted function.
PHP Extract Method example
PHP Extract Function example
To extract a PHP function or method:
- In the editor, select a block of code to be transformed into a function or method.
- On the main menu or on the context menu of the selection, choose or press Ctrl+Alt+M.
- Specify the name of the new function or method.
- If a method is to be extracted, choose the relevant access modifier for it in the Visibility area:
- Configure the output of the new method or function in the Return output variable(s) through area.
The Output variable(s) read-only field displays all the variables that make up the output of the selected code fragment. Specify the way in which the new method or function will return these variables to the callee.
- To have the output variables returned by value, select the Return statement option. The result of this choice depends on the number of detected output variables. If there is exactly one output variable, it will be used as the return value. If the selection outputs several variables, these variables will be returned as an array.
- To have the output variables returned by reference, select the Parameter(s) passed by reference option. In this case, no return statement will be generated. Instead, all the detected output variables will be added to the list of input parameters. Their names will be prepended with an ampersand
&both in the Parameters list and in the declaration of the new method/function, as shown in the Signature preview read-only area.
- In the Parameters area, configure the input for the new function or method.
Originally, the list contains the variables that PhpStorm has detected as the input for the new method or function. However, if you have chosen to return the new method/function output by reference, the list also contains all the output variables.
If necessary, rename the desired parameters, by double-clicking the corresponding parameter lines and entering new names.
- Optionally, to have PhpStorm transform tail break or continue statements if the selection contains any, select the Replace tail "break/continue" statements with return statements check box.
- View and check the declaration of the function or method to be generated in the Signature preview read-only area.