PhpStorm: Refactoring With Extract Variable cover image

PhpStorm: Refactoring With Extract Variable

Scott Keck-Warren • February 24, 2025

PHPStorm has some amazing refactoring support build into it. One of the refactoring tools I reach for on a common basis is the the extract variable refactoring which allows us to take a statement and turn it into a variable.

For example, we may have the code below and realize we need to modify the number 42 before we return it.

function getTheAnswer(): int
{
    return 42;
}

By performing the extract variable refactoring we'll create the following code:

function getTheAnswer(): int
{
    $i = 42;
    return $i;
}

PhpStorm can perform this refactoring for us by selecting the text we want to extract into a variable and then using the keyboard shortcut command(⌘) + option(⌥) + V.

It will suggest a variable name for us but we can replace it with whatever makes the most sense for us.

Screenshot with basic history

If we have multiple copies of the same section of code it will prompt us to see how much of the code we want to replace.

Images

Shareable Image