PhpStorm 2024.2 Help

Extract parameter

The Extract Parameter refactoring is used to add a new parameter to a function declaration and to update the function calls accordingly.

Extracting a parameter
  1. In the editor, place the caret within the expression to be replaced by the parameter.

  2. Do one of the following:

    • Press Ctrl+Alt+P.

    • Choose Refactor | Extract/Introduce | Parameter from the main menu.

    • Choose Refactor | Introduce Parameter from the context menu.

    • On the floating toolbar that appears when a code fragment is selected, click Extract and select Parameter.

  3. If more than one expression is detected for the current caret position, the Expressions list appears. If this is the case, click the expression to select it. Alternatively, press Up or Down to navigate to the expression of interest, and then press Enter to select it.

  4. Type the parameter name in the box with a red border.

  5. To complete the refactoring, press Tab or Enter.

    If you haven't completed the refactoring and want to cancel the changes you have made, press Escape.

    Note that sometimes you may need to press the corresponding key more than once.

PHP Example

In the example below, a new parameter $c is added to the Calculate() function to replace 10:

Before

After

class Class1 { public function Calculate($i){ while ( $i < 10 ) { $i = $i + 1; }; return $i; } public function DisplaySum(){ $a = 1; $result = $this -> Calculate($a); echo "The final result is " . $result; } }
class Class1 { public function Calculate($i,$c){ while ( $i < $c ) { $i = $i + 1; }; return $i; } public function DisplaySum(){ $a = 1; $result = $this -> Calculate($a, 10); echo "The final result is " . $result; } }

JavaScript Example

Before

After

A new parameter will be added to this function to replace the 1's:

function calculate_sum(i) { alert('Adding ' + 1 + ' to ' + i); return (1 + i); } function show_sum() { alert('Result: ' + calculate_sum(5)); }

The new parameter i2 has been added as an optional parameter:

function calculate_sum(i, i2) { i2 = i2 || 1; alert('Adding ' + i2 + ' to ' + i); return (i2 + i); } function show_sum() { // The function call has not changed: alert('Result: ' + calculate_sum(5)); }

A new parameter will be added to this function to replace the 1's. When adding a new parameter we'll specify that it should be a required one.

function calculate_sum(i) { alert('Adding ' + 1 + ' to ' + i); return (1 + i); } function show_sum() { alert('Result: ' + calculate_sum(5)); }

The new parameter i2 has been added as a required parameter:

function calculate_sum(i, i2) { alert('Adding ' + i2 + ' to ' + i); return (i2 + i); } function show_sum() { alert('Result: ' + calculate_sum(5, 1)); }

For more information, refer to Extract Parameter in JavaScript.

Last modified: 08 October 2024