简体   繁体   English

如何从子类的实例调用父类的函数?

[英]How do I call the functions of the parent class from an instance of a subclass?

normally, (in subtype definition) I use 通常,(在子类型定义中)我使用

function enable() {
  parent::enable();
 }

 function disable() {
  parent::disable();
 }

and then I call $subtypeinstance->enable() 然后我调用$ subtypeinstance-> enable()

but can I also use something like 但我也可以使用类似

$subtypeinstance->parent::enable() 

or 要么

(SupertypeName)$subtypeinstance->enable()

Based on your comment: 根据您的评论:

it'd be useful when you don't wannt to override functions of supertype in each of the subtypes 当您不希望在每个子类型中覆盖超类型的功能时,这将非常有用

If all your method does is call the method of the same name of its parent , you don't need the function at all. 如果您的方法所做的只是调用与parent名称相同的方法,则根本不需要该函数。 Functions are inherited from the parent class, that's mostly the whole point of inheritance. 函数是从父类继承的,这几乎是继承的全部要点。

class Parent {
    public function enable() {
        echo 'enabled';
    }
}

class Child extends Parent { }

$child = new Child;
$child->enable();  // outputs 'enabled'

So I suspect you don't actually need what you're asking for. 因此,我怀疑您实际上并不需要您要的东西。 Otherwise, I don't think it's possible. 否则,我认为不可能。

You can actually call Parent::enable() or parent::enable() (ie class name or parent keyword) as PHP makes no distinction between static and instance calls and passes an instance anyway. 实际上,您可以调用Parent::enable()parent::enable() (即类名或parent关键字),因为PHP不会区分静态调用和实例调用,并且始终传递一个实例。

class Foo {
    public $x;
    public function bar() {
        echo "Foo::bar(), x is " . $this->x . "\n";
    }
}

class FooChild extends Foo {
    public function bar() {
        echo "FooChild::bar(), x is " . $this->x . "\n";
        Foo::bar();
        parent::bar();
    }
}

$foo = new Foo();
$foo->x = 42;
$foo->bar();

$fooc = new FooChild();
$fooc->x = 43;    
$fooc->bar();

Output: 输出:

Foo::bar(), x is 42
FooChild::bar(), x is 43
Foo::bar(), x is 43
Foo::bar(), x is 43

The parent keyword reference explains this and gives the same example. parent关键字参考对此进行了解释,并给出了相同的示例。

I have found out that 我发现

$this->function()

calls the supertype methods with no need for overriding parent functions in subtypes 调用超类型方法,而无需覆盖子类型中的父函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM