PhpStorm 2025.2 Help

上移成员,下移成员

向上拉取成员 重构允许您将类成员移动到父类。 当您从类层次结构的底部开始添加功能,然后意识到它也可以用于更常见的情况时,这可能会有所帮助(否则,代码的某些部分可能会对父类变得过时,但对其子类之一仍然有效)。 使用 上移成员 重构,您无需手动从一个类复制方法或字段,粘贴到另一个类中并修复成员中的内部引用。

向下推送成员 重构通过将类成员移动到子类来帮助清理类层次结构。 然后,这些成员仅重新定位到直接子类中。

上移成员

  1. 选择要移动到父类的类。

  2. 从主菜单或上下文菜单中调用 重构 | 上移成员上移成员 对话框出现。

  3. 选择目标对象(父类)。

  4. 成员 部分中,选择您想要移动的成员。

  5. 单击 重构 以将选定的成员上移到目标位置。

示例

假设您有一个类 Car ,它扩展了父类 Vehicle。 让我们将 printPassengers() 方法和 $numOfPassengers 字段从 Car 移动到 Vehicle

  1. 将光标放在类 Car 内,并从上下文菜单中选择 重构 | 上移成员...

  2. 在打开的 上拉成员对话框 中,选中 printPassengers()$numOfPassengers 旁边的复选框。 PhpStorm 通知您 $numOfPassengers 的可见性将从 private 更改为 protected

    ps_pull_members_dialog_php_example.png
  3. 点击 重构

重构后,类将如下所示:

abstract class Vehicle { } class Car extends Vehicle { protected $weight; private $numOfPassengers; function __construct($weight,$numOfPassengers) { $this->weight = $weight; $this->numOfPassengers = $numOfPassengers; } protected function printWeight() { echo 'Weight = ' . $this->weight; } protected function printPassengers() { echo 'Number of passengers = ' . $this->numOfPassengers; } }
abstract class Vehicle { protected $numOfPassengers; protected function printPassengers() { echo 'Number of passengers = ' . $this->numOfPassengers; } } class Car extends Vehicle { protected $weight; function __construct($weight,$numOfPassengers) { $this->weight = $weight; $this->numOfPassengers = $numOfPassengers; } protected function printWeight() { echo 'Weight = ' . $this->weight; } }

下移成员

  1. 在编辑器中,打开需要下移成员的类。

  2. 从主菜单或上下文菜单中选择 重构 | 向下推送成员下推成员对话框 显示要下移的成员列表。

  3. 要下推的成员 区域中,选择您想要移动的成员。 请注意,光标所在的成员已被选中。

    如果下移成员可能导致问题,您将收到红色高亮的通知。 这意味着,如果情况未被处理,重构后将会出现错误。 PhpStorm 会提示您一个“检测到问题”对话框,您可以选择忽略或修复问题。

  4. 预览并应用更改。

示例

假设您有一个 Vehicle 类,一个扩展了 VehicleCar 类,以及另一个也扩展了 VehicleTruck 类。 让我们将 start() 方法从父类 Vehicle 下移到其子类 CarTruck

  1. 将光标放在 Car 类中,并从上下文菜单中选择 重构 | 向下推送成员

  2. 在打开的 下推成员对话框 中,选中 start() 旁边的复选框,并单击 重构

    ps_pull_members_dialog_php_example.png

重构后,类将如下所示:

abstract class Vehicle { protected $code; public $name; protected function start() { echo "Let's start!"; } } class Car extends Vehicle { protected $weight; function __construct($weight) { $this->weight = $weight; } } class Truck extends Vehicle { protected $length; function __construct($length) { $this->length = $length; } }
abstract class Vehicle { protected $code; public $name; } class Car extends Vehicle { protected $weight; function __construct($weight) { $this->weight = $weight; } protected function start() { echo "Let's start!"; } } class Truck extends Vehicle { protected $length; function __construct($length) { $this->length = $length; } protected function start() { echo "Let's start!"; } }
最后修改日期: 2025年 9月 26日