构造函数参数不继承到 children?
Constructor argument not inheriting down to children?
我是 php 的新手,尤其是 oop。我有一段我认为会 return:
的测试代码
What is the result?8
What is the result?8
但是,我得到的是:
What is the result?5
What is the result?8
传递给 class 实例的参数似乎没有分配给 x。我也试过 echo $second->x
,但 return 没什么。
我是不是弄错了一些代码,是我对继承有什么误解还是对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();
?>
如果重写一个方法,比如本例中的构造函数,则需要显式调用父 class 方法,如下所示:
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"
您的 Second
class
稍作更新
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
我是 php 的新手,尤其是 oop。我有一段我认为会 return:
的测试代码What is the result?8
What is the result?8
但是,我得到的是:
What is the result?5
What is the result?8
传递给 class 实例的参数似乎没有分配给 x。我也试过 echo $second->x
,但 return 没什么。
我是不是弄错了一些代码,是我对继承有什么误解还是对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();
?>
如果重写一个方法,比如本例中的构造函数,则需要显式调用父 class 方法,如下所示:
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"
您的 Second
class
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