kiler129
kiler129

Reputation: 1154

Calling an overridden parent method

In the sample code below, the method test() in parent class Foo is overridden by the method test() in child class Bar. Is it possible to call Foo::test() from 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();

Upvotes: 35

Views: 42174

Answers (5)

iruwl
iruwl

Reputation: 181

Just set visibility levels at $text property.

private $text = "world\n";

Upvotes: 0

Bence Szalai
Bence Szalai

Reputation: 922

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:

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();

Upvotes: -1

Adam Zalcman
Adam Zalcman

Reputation: 27233

Use parent:: before method name, e.g.

parent::test();

See parent

Upvotes: 49

jeanreis
jeanreis

Reputation: 908

Judging by your comments on the pastebin, I'd say you can't.

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();
    }
}

Upvotes: -2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272772

parent::test();

(see Example #3 at http://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php)

Upvotes: 6

Related Questions