dtqpw68806 2012-02-13 08:26
浏览 69
已采纳

为什么不能在子类中使用常量值覆盖父变量? (PHP)

I have a class first where $name is set to 'bob'. In the child class, I set $name to 'Karen' but it doesn't work.

In my echo statements, the 1st one says "bob" instead of 'Karen'. The second one, using a child class method, works though.

Why is this behavior?

class First {

    public $name;

    public function __construct() {

        $this->name = 'bob';
    }
}

class Third extends First {

    public $name = 'Karen';
    public function set_name ($name) {
        $this->name = $name;
    }
}

$instance_of_third = new Third;
$third_name = $instance_of_third->name;

echo "<br />We're looking for Karen: $third_name<br />";
// $third_name here is 'bob' from parent class

$instance_of_third->set_name("Karen");
$third_name = $instance_of_third->name;
// $third_name here is 'Karen' only after using set_name()
echo "<br />We're looking for Karen: $third_name<br />";

EDIT: I added 2 lines showing what the output was exactly.

Even though $name is explicitly set to 'Karen' in child class, it shows as 'bob' unless the set_name() function is used to change it.

  • 写回答

6条回答 默认 最新

  • dongtuan5367 2012-02-13 08:40
    关注

    Because your Third does not have it's own constructor, it will inherit the constructor from First. Inheritance creates an behaves-as relationship between supertype and subtype.

    So when you create a new instance of Third, the instance will have a $name property of 'Karen', but then the inherited constructor will get called. And that sets the name to Bob. If you don't want that behavior in the subtype, you have to add an empty constructor to Third, e.g.

    class Third extends First
    {
        public function __construct()
        {
            // prevents parent First::__construct
        }
    }
    

    demo

    An alternative would be to remove the ctor (or at least not set $name in it) and preset the $name property in the parent to Bob. Then your initial idea would work, e.g.

    class First
    {
        public $name = 'Bob';
    }
    
    class Third extends First
    {
        public $name = 'Karen';
    }
    

    demo

    Please check the chapters on Inheritance and Visibility in the PHP Manual:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)