Frage

I've been creating abstract classes and interfaces to force consistency within my Wordpress plugins, but I'm never sure if I should be invoking inherited functions by using parent::some_function() or using $this->some_function()? Since jumping back and forth between the two looks super messy/confusing.

For Example: Using getter/setters should I be:

$this->get_my_var(); // indicating nothing about its origins except through comments

or

parent::get_my_var(); // indicating you can find it in the parent
War es hilfreich?

Lösung

They're not the same thing.

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"

If instead you had:

class B extends A {
    ...
    public function bar() {
        return parent::foo();
    }
}

var_dump($b->bar()); // just "a"

The foo function of B adds something to the foo function of A. This is a common pattern.

Whether calling parent::foo in bar is good or not depends on your design choices, I personally think it's a little iffy. Calling parent::foo in foo is fine by the way.

Andere Tipps

I only use parent:: in constructors, destructors and static methods. For everything else I trust people to know how object inheritance works. I would use $this->get_my_var();

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top