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

PHP OOP:子类构造方法无法继承父类更新后的protected属性问题

嘿,我一眼就看出问题出在哪啦!

问题根源:子类未触发父类构造逻辑

当你实例化子类test2时,它的构造函数直接覆盖了父类test的构造函数——PHP里子类构造默认不会自动执行父类的构造代码。这就导致父类里把$testing改成changed的逻辑根本没跑,子类实例里的$testing还是初始的'test',自然看不到你期望的changed值。

修复方案:手动调用父类构造函数

只需要在子类的构造函数开头,用parent::__construct()触发父类的构造逻辑,这样父类对$testing的修改会先执行,之后子类再进行自己的属性操作。

修改后的代码如下:

class test { 
    protected $testing = 'test'; 
    function __construct(){ 
        echo "The Test class has loaded (".$this->testing.")\n"; 
        $this->testing='changed'; 
        echo "Updated to (".$this->testing.")\n"; 
    } 
} 
class test2 EXTENDS test { 
    function __construct(){ 
        // 先调用父类构造,执行属性修改逻辑
        parent::__construct();
        echo "The Test2 class has loaded (".$this->testing.")\n"; 
        $this->testing='updated'; 
        echo 'The string has been updated to ('.$this->testing.')'."\n"; 
    } 
} 
$blah = new test(); 
$blah2 = new test2(); 
验证输出结果

运行修改后的代码,就能得到你想要的输出:

The Test class has loaded (test)
Updated to (changed)
The Test class has loaded (test)
Updated to (changed)
The Test2 class has loaded (changed)
The string has been updated to (updated)

这里补充个小知识点:每个类实例都是独立的,父类实例$blah的属性修改不会直接影响子类实例$blah2。但通过调用父类构造,子类实例自己会执行一遍父类的属性修改逻辑,所以能拿到changed这个值。如果想让所有实例共享同一个属性值,那得把$testing改成静态属性(static protected $testing = 'test';),不过从你的需求来看,上面的修复就完全够用啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:18:39