[英]Use method of parent class when extending
Probably a silly question.. but how do I correctly use the methods of class Test in class Testb without overriding them? 可能是一个愚蠢的问题。但是,如何在不覆盖它们的情况下正确使用Testb类中的Test方法呢?
<?php
class Test {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
<?php
class Testb extends Test {
public function __construct() {
parent::__construct($name);
}
}
<?php
include('test.php');
include('testb.php');
$a = new Test('John');
$b = new Testb('Batman');
echo $b->getName();
You need to give the Testb
constructor a $name
parameter too if you want to be able to initialize it with that argument. 如果您希望能够使用该参数对其进行初始化,则还需要给Testb
构造函数一个$name
参数。 I modified your Testb
class so that its constructor actually takes an argument. 我修改了您的Testb
类,以便其构造函数实际上接受一个参数。 The way you currently have it, you should not be able to initialize your Testb
class. 当前的方式,您将无法初始化Testb
类。 I use the code as follows: 我使用如下代码:
<?php
class Test {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class Testb extends Test {
// I added the $name parameter to this constructor as well
// before it was blank.
public function __construct($name) {
parent::__construct($name);
}
}
$a = new Test('John');
$b = new Testb('Batman');
echo $a->getName();
echo $b->getName();
?>
Perhaps you do not have error reporting enabled? 也许您没有启用错误报告? In any event, you can verify my results here: http://ideone.com/MHP2oX 无论如何,您可以在这里验证我的结果: http : //ideone.com/MHP2oX
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.