我一直在创建抽象类和接口来强制我的Wordpress插件内的一致性,但我从不确定我是否应该通过使用parent::some_function()或使用$this->some_function()来调用继承函数?因为在两者之间来回跳跃看起来超级混乱/令人困惑。
例如:使用getter/setter应该是:
$this->get_my_var(); // indicating nothing about its origins except through comments
或
parent::get_my_var(); // indicating you can find it in the parent
它们不是一回事。
class A {
protected function foo() {
return "a";
}
}
class B extends A {
protected function foo() {
return parent::foo() . "b";
}
public function bar() {
return $this->foo();
}
}
$b = new B();
var_dump($b->bar()); // "ab"
如果你有:
class B extends A {
...
public function bar() {
return parent::foo();
}
}
var_dump($b->bar()); // just "a"
B
的foo
函数增加了A
的foo
函数。这是一个常见的模式。
在bar
中调用parent::foo
是否好取决于你的设计选择,我个人认为这有点可疑。在foo
中调用parent::foo
是可以的。
我只在构造函数、析构函数和静态方法中使用parent::
。对于其他事情,我相信人们知道对象继承是如何工作的。我会使用$this->get_my_var();