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

PHP面向对象编程:继承中调用protected方法报错问题咨询

PHP中调用protected方法报错的原因

问题代码

//((inheritance))

class ParentClass
{
    public function public_message()
    {
        echo "This is a Public message" . "<br>" . "from Parent class .";
    }

    protected function protected_message()
    {
        echo "This is a Protected message" . "<br>" . "from Parent class .";
    }
}


class Child extends ParentClass
{
}

$obj = new Child();
$obj->protected_message();

运行上述代码时出现了错误!但根据认知,protected方法(或属性)在继承关系中是可以正常使用的,想请教这一问题的原因。


错误原因

你混淆了protected成员的访问范围:

  • protected成员的可见性是类继承体系内部可见,也就是说只能在父类、子类的成员方法内部访问,不能在类的外部(比如全局作用域)直接通过实例调用。
  • 你的代码里是在类外部通过$obj->protected_message()直接调用protected方法,这违反了PHP的访问控制规则,所以会报错。

正确用法示例

如果要使用父类的protected方法,需要在子类的内部方法中调用:

class ParentClass
{
    public function public_message()
    {
        echo "This is a Public message" . "<br>" . "from Parent class .";
    }

    protected function protected_message()
    {
        echo "This is a Protected message" . "<br>" . "from Parent class .";
    }
}

class Child extends ParentClass
{
    // 在子类内部定义方法,调用父类的protected方法
    public function invoke_protected_method()
    {
        $this->protected_message();
    }
}

$obj = new Child();
$obj->invoke_protected_method(); // 正常执行,输出protected方法内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 06:54:50