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

如何在子类中访问父类的非静态属性?报错解决方案

子类访问父类同名非静态属性的正确方式

你遇到的致命错误是因为误用了parent::$var语法——parent::是用来访问父类的静态成员或被重写的方法的,而$var是非静态实例属性,不能用静态访问方式获取。

下面给出两种可行的解决方案:

方案1:通过父类方法间接获取属性

在父类中添加一个返回该属性的方法,子类通过parent::调用这个方法,就能拿到父类的属性值:

class First
{
    public $var = 'First Non-Static Property';

    public function __construct()
    {
        echo $this->var;
    }

    // 新增方法返回父类的$var
    public function getParentVar()
    {
        return $this->var;
    }
}

class Second extends First
{
    public $var = 'Second Non-Static Property';

    public function __construct()
    {
        // 调用父类方法获取父类属性
        echo parent::getParentVar();
    }
}

$object = new Second(); // 输出:First Non-Static Property

方案2:用反射类读取父类属性的默认值

如果无法修改父类代码,可以借助PHP的反射机制,直接读取父类中该属性的默认值:

class First
{
    public $var = 'First Non-Static Property';

    public function __construct()
    {
        echo $this->var;
    }
}

class Second extends First
{
    public $var = 'Second Non-Static Property';

    public function __construct()
    {
        $reflection = new ReflectionClass(parent::class);
        $parentProperty = $reflection->getProperty('var');
        echo $parentProperty->getDefaultValue(); // 输出:First Non-Static Property
    }
}

$object = new Second();

补充说明

PHP中,当子类定义了和父类同名的非静态属性时,子类实例的该属性会直接覆盖父类的对应属性,所以直接用$this->var只能拿到子类的属性值。parent::本身不支持直接访问非静态实例属性,必须通过父类方法或者反射这类间接方式获取父类的属性内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 10:57:42