Question

normally, (in subtype definition) I use

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

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

and then I call $subtypeinstance->enable()

but can I also use something like

$subtypeinstance->parent::enable() 

or

(SupertypeName)$subtypeinstance->enable()
Was it helpful?

Solution

You can actually call Parent::enable() or parent::enable() (i.e. class name or parent keyword) as PHP makes no distinction between static and instance calls and passes an instance anyway.

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.

OTHER TIPS

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. 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.

I have found out that

$this->function()

calls the supertype methods with no need for overriding parent functions in subtypes

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top