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 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划