我是php的新手,尤其是oop。我有这段测试代码,我认为会返回:
What is the result?8
What is the result?8
但是,相反,我得到了:
What is the result?5
What is the result?8
传递给类实例的参数似乎没有被分配给x。我也尝试过echo $second->x
而不返回任何内容。
我是否有一些错误的代码,我是否误解了继承问题,或者我误解了constructors
的某些内容?
以下是代码:
<?php
class First{
public function __construct($x){
$this->x = $x;
echo "What is the result?";
}
}
class Second extends First{
public function calculation(){
$z=5;
return $x+$z."<br />";
}
}
class Third extends First{
public function calculation(){
$z=5;
$x=3;
$y=$x+$z;
return $y."<br/>";
}
}
$second = new Second('3');
echo $second->calculation();
$third = new Third('3');
echo $third->calculation();
?>
答案 0 :(得分:1)
如果覆盖方法,就像本例中的构造函数一样,则需要显式调用父类方法,如下所示:
class A {
public function __construct() {
var_dump(__METHOD__);
}
}
class B extends A {
public function __construct() {
var_dump(__METHOD__);
// call parent constructor
parent::__construct();
}
}
$b = new B();
输出:
string(14) "B::__construct"
string(14) "A::__construct"
答案 1 :(得分:1)
在Second
班级
class Second extends Test{
public function calculation(){
$z=5;
return $this->x+$z."<br />";//$x should be $this->x
}
}
<强>输出:强>
What is the result?8
What is the result?8