如何在 PHP 中调用 super?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1961907/
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
How to call super in PHP?
提问by openfrog
I have a classBwhich extends classA.
我有一个classB扩展classA.
In both classAandclassBI define the method fooBar().
在两者中classA,classB我都定义了方法fooBar()。
In fooBar()of classBI want to call fooBar()of classAat the beginning.
在fooBar()的classB我想在开始时调用fooBar()的classA。
Just the way I'm used to, from Objective-C. Is that possible in PHP? And if so, how?
就像我习惯的那样,来自 Objective-C。这在 PHP 中可能吗?如果是这样,如何?
回答by just somebody
parent::fooBar();
Straight from the manual:
直接从手册:
The ... double colon, is a token that allows access to ... overridden properties or methods of a class.
...
Example #3 Calling a parent's method
<?php class MyClass { protected function myFunc() { echo "MyClass::myFunc()\n"; } } class OtherClass extends MyClass { // Override parent's definition public function myFunc() { // But still call the parent function parent::myFunc(); echo "OtherClass::myFunc()\n"; } } $class = new OtherClass(); $class->myFunc(); ?>
... 双冒号是一个令牌,允许访问 ... 类的重写属性或方法。
...
Example #3 调用父方法
<?php class MyClass { protected function myFunc() { echo "MyClass::myFunc()\n"; } } class OtherClass extends MyClass { // Override parent's definition public function myFunc() { // But still call the parent function parent::myFunc(); echo "OtherClass::myFunc()\n"; } } $class = new OtherClass(); $class->myFunc(); ?>
回答by Spoike
Just a quick note because this doesn't come up as easy on Google searches, and this is well documented in php docs if you can find it. If you have a subclass that needs to call the superclass's constructor, you can call it with:
只是一个简短的说明,因为这在谷歌搜索中并不容易,如果你能找到它,这在 php 文档中有很好的记录。如果您有一个需要调用超类构造函数的子类,您可以使用以下命令调用它:
parent::__construct(); // since PHP5
An example would be if the super class has some arguments in it's constructor and it's implementing classes needs to call that:
一个例子是,如果超类在它的构造函数中有一些参数,并且它的实现类需要调用它:
class Foo {
public function __construct($lol, $cat) {
// Do stuff specific for Foo
}
}
class Bar extends Foo {
public function __construct()(
parent::__construct("lol", "cat");
// Do stuff specific for Bar
}
}
You can find a more motivating example here.
您可以在此处找到更励志的示例。

