PHP构造函数:Will an";继承的;构造函数是否使用继承的或父类重写的方法?
假设我有一节课PHP构造函数:Will an";继承的;构造函数是否使用继承的或父类重写的方法?,php,inheritance,constructor,Php,Inheritance,Constructor,假设我有一节课 class Item { public function __construct($id) { if(!empty($id)) { $this->doSomethingWithID($id); } } public function dummyMethod() { //does Something. } protected function doSomethingWithID($id) { //Does somet
class Item {
public function __construct($id) {
if(!empty($id)) {
$this->doSomethingWithID($id);
}
}
public function dummyMethod() {
//does Something.
}
protected function doSomethingWithID($id) {
//Does something with the ID
}
}
如果我继承了这样的类:
class Product extends Item {
public function __construct() {
parent::__construct();
}
protected function doSomethingWithID($id) {
//OVERRIDES THE PARENT FUNCTION
}
}
Product类是否将使用重写的方法?或者它会使用父方法吗?越具体的东西,它在代码中的优先级就越高
方法与父母同名的儿童优先。您可以通过说
super.method()
来调用父类方法。您已经在继承的类中声明了一个新的构造方法,因此它将使用该方法,但是当继承的类调用父类构造方法时,它将使用该方法。您可以尝试一下,但没有办法,因为我正在处理别人的代码,没有找到一种安全的测试方法,只是想确保它按照我认为的方式工作,这样我就可以继续分析它。谢谢,没错。如果子类构造函数使用的方法在其类中被重写,它将不会使用父类的方法。对不起,我误解了你的问题吗?不,我给你一个理由,你说的是子类方法优先。