不使用__constructor能否实现PHP带私有属性的类继承功能?
问题解答
结论:可以不使用__constructor实现需求,你的现有代码只需做小幅调整即可正常运行。
现有代码直接运行会输出空的水果名称和颜色,问题根源如下:
- 你实例化
new Strawberry("Strawberry", "red")时传入的两个参数,没有被任何构造逻辑接收处理,父类Fruit中定义的patients()是普通公共方法,不会在实例化时自动触发 - 你定义的
private $name、private $color就是私有属性,术语表述正确,这类属性仅允许在定义它的类内部访问,禁止外部、子类直接读写,完全符合你「属性私有存储」的要求,现有逻辑中通过父类公共方法操作私有属性的写法是正确的。
无需__constructor的修改方案
手动调用patients()方法完成私有属性赋值即可,调整后代码如下:
<?php class Fruit { private $name; private $color; public function patients($name, $color) { $this->name = $name; $this->color = $color; } public function intro() { echo "The fruit is {$this->name} and the color is {$this->color}."; } } // Strawberry 继承自 Fruit class Strawberry extends Fruit { public function message() { $this->intro(); } } $strawberry = new Strawberry(); // 手动调用赋值方法完成私有属性初始化 $strawberry->patients("Strawberry", "red"); $strawberry->message(); ?>
修改后运行将正常输出:The fruit is Strawberry and the color is red.
补充说明
如果你想保留实例化时直接传参的写法,又不想用__constructor,仅PHP 4.x老旧版本支持「和类名同名的方法作为构造函数」的规则,你需要把父类的patients()方法改名为Fruit(),同时在子类中定义同名构造方法调用父类构造,但这种写法在PHP 7.0及以上版本会抛出废弃警告,完全不推荐生产环境使用。
内容的提问来源于stack exchange,提问作者deeku ahlam
相关产品推荐
相关产品推荐

