You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP8中如何在父类函数参数中定义可指代当前子类的类型?

解决方案

PHP 8.0 及以上版本(最简便实现)

直接使用PHP 8.0引入的static参数类型即可,该类型会触发后期静态绑定,指向实际调用方法的子类类型,完全不需要在每个子类中重写方法。
实现代码如下:

class Car
{
    protected function beforeSaving(static $resource)
    {
        // 方法逻辑
    }
}

class Audi extends Car
{
    // 无需重写beforeSaving方法
}

class Toyota extends Car
{
    // 无需重写beforeSaving方法
}

效果验证:调用(new Audi())->beforeSaving(new Toyota())时,PHP会直接抛出类型错误,符合参数仅接收当前子类实例的要求。

PHP 7.x 及更低版本兼容方案

低版本PHP不支持将static作为参数类型,可通过两种方式实现需求:

方案1:静态分析校验

配合PHPStan、Psalm等静态分析工具,在PHPDoc中声明参数为static类型,编译阶段即可检测到类型错误,IDE也会给出对应的类型提示:

class Car
{
    /**
     * @param static $resource
     */
    protected function beforeSaving(Car $resource)
    {
        // 方法逻辑
    }
}

方案2:运行时强制校验

在父类方法中添加运行时类型判断,不符合要求直接抛出类型错误:

class Car
{
    /**
     * @param static $resource
     */
    protected function beforeSaving(Car $resource)
    {
        if (!$resource instanceof static) {
            throw new \TypeError(sprintf(
                'Argument 1 passed to %s::beforeSaving() must be an instance of %s, %s given',
                __CLASS__,
                static::class,
                get_debug_type($resource)
            ));
        }
        // 方法逻辑
    }
}

内容的提问来源于stack exchange,提问作者Firze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 01:27:02