php 调用重写的父方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8073471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling an overridden parent method
提问by kiler129
In the sample code below, the method test()in parent class Foois overridden by the method test()in child class Bar. Is it possible to call Foo::test()from Bar::test()?
在以下示例代码,该方法test()在父类Foo是由该方法覆盖test()在子类Bar。是否有可能调用Foo::test()从Bar::test()?
class Foo
{
$text = "world\n";
protected function test() {
echo $this->text;
}
}// class Foo
class Bar extends Foo
{
public function test() {
echo "Hello, ";
// Cannot use 'parent::test()' because, in this case,
// Foo::test() requires object data from $this
parent::test();
}
}// class Bar extends Foo
$x = new Bar;
$x->test();
回答by Adam Zalcman
回答by Oliver Charlesworth
parent::test();
(see Example #3 at http://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php)
(参见http://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php 上的示例 #3 )
回答by iruwl
Just set visibility levels at $text property.
只需在 $text 属性中设置可见性级别。
private $text = "world\n";
回答by sbnc.eu
Calling a parent method may be considered bad practice or code smell and may indicate programming logic that can be improved in a way, that the child doesn't have to call the parent. A good generic description is provided by Wikipedia.
调用父方法可能被认为是不好的做法或代码异味,并且可能表明可以以某种方式改进的编程逻辑,孩子不必调用父方法。维基百科提供了一个很好的通用描述。
An implementation without calling parent would look like:
不调用 parent 的实现如下所示:
abstract class Foo
{
$text = "world\n";
public function test() {
$this->test_child();
echo $this->text;
}
abstract protected function test_child();
}// class Foo
class Bar extends Foo
{
protected function test_child() {
echo "Hello, ";
}
}// class Bar extends Foo
$x = new Bar;
$x->test();
回答by jeanreis
Judging by your comments on the pastebin, I'd say you can't.
从你对 pastebin 的评论来看,我会说你不能。
Maybe if you had something like this?
也许如果你有这样的事情?
class foo {
public function foo($instance = null) {
if ($instance) {
// Set state, etc.
}
else {
// Regular object creation
}
}
class foo2 extends foo {
public function test() {
echo "Hello, ";
// New foo instance, using current (foo2) instance in constructor
$x = new foo($this);
// Call test() method from foo
$x->test();
}
}

