PHP静态函数回传类型:static 与 self 的差异
这是AI解释的,搬到这里来免得自己忘了。
在PHP静态方法(static method)的回传类型提示中,使用 static 和 self是两个常见的选项。它们都表示方法可能返回一个类实例,但它们在继承和多态性(Polymorphism)方面的表现有所不同。
使用 self (类型被锁定)
当在 ParentClass 中使用 : ?self 时,回传类型永远锁定为 ParentClass。
class ParentClass {
// 尽管 new static() 实际创建的是 ChildClass 实例,
// 但类型提示被锁定在 ParentClass。
public static function factory(): self {
return new static();
}
}
class ChildClass extends ParentClass {}
// 呼叫 ChildClass::factory()
$instance = ChildClass::factory();
// 问题:类型提示是ParentClass,无法使用ChildClass独有的方法。
// 静态分析工具会认为$instance是ParentClass类型。使用 static (类型更灵活)
class ParentClass {
// 类型根据实际调用的类而定,完美支持多态。
public static function factory(): static {
return new static();
}
}
class ChildClass extends ParentClass {}
// 呼叫 ChildClass::factory()
$instance = ChildClass::factory();
// 结果:类型提示正确地识别为ChildClass。
// 结论:这是实现可继承静态方法(如链式调用或工厂模式)的标准方式。对于需要被子类继承,并且要返回自身类实例的静态方法,您应该优先使用 static。
只有当您有特殊需求,需要确保无论在哪儿调用,返回的类型必须是原始定义方法的那个父类时,才使用 self。在绝大多数面向对象编程(OOP)的继承场景中,static 才是您需要的。