Extract expressions into variables in PhpStorm
Learn how to extract repeated expressions into variables to improve code clarity and simplify maintenance.
Lesson Content
Sometimes an expression is repeated within the same block of code. For example, $renderBlock->getItem() appears multiple times, and so does $renderBlock->getParentBlock(). PhpStorm can extract either expression into a variable and replace the repeated calls.
Place the cursor somewhere inside the getItem() call, then press Cmd+Option+V. On Windows, use Ctrl+Alt+V. PhpStorm opens the Expressions dialog and selects the expression under the cursor.
PhpStorm detects how many times the expression appears and lets you replace only the current occurrence or all occurrences. Select the first expression, choose the option to replace all two occurrences, and press Enter. PhpStorm creates a variable and replaces both calls:
$item = $renderBlock->getItem();The variable name is based on an intelligent guess from the expression. You can repeat the process for $renderBlock->getParentBlock(): place the cursor inside the call, press Cmd+Option+V or Ctrl+Alt+V, select the expression, and choose to replace all three occurrences.
PhpStorm suggests abstractBlock, along with alternate names such as parentBlock. You can select one of the suggestions and press Enter, or start typing to provide your own name. Name this variable parent, and PhpStorm replaces every occurrence:
$parent = $renderBlock->getParentBlock();Extracting repeated expressions into variables cleans up the code and makes it easier to understand and reason about.
Join the discussion!
Comments
Want to comment on this lesson?
Log in to leave comments.