-1

In PHP OOP, it is possible to call an object's parent method, by externally referencing that object?

Class ObjectOne {
    protected function method() {
        // Does something simple
    }
}

Class ObjectTwo extends ObjectOne {
    protected function method() {
        $temp = clone $this;
        $this->change_stuff();
        if(parent::method()) {
            // Do more stuff here
            $temp->method();
            // This will call this method, not the parent's method.
        }
    }

    protected function change_stuff() {
        // Change this object's stuff
    }
}

I can't call parent::method() because this will cause the current object to execute it's method. I want the $temp ones's instead.

SOLVED

I solved it by writing another function that calls the parent::update() method from inside the class:

Class ObjectOne {
    protected function method() {
        // Does something simple
    }
}

Class ObjectTwo extends ObjectOne {
    protected function method() {
        $temp = clone $this;
        $this->change_stuff();
        if(parent::method()) {
            // Do more stuff here
            $temp->update_parent();
            // This will call this method, not the parent's method.
        }
    }

    protected function change_stuff() {
        // Change this object's stuff
    }

    protected function update_parent() {
        return parent::update();
    }
}
4

2 回答 2

4

$temp->parent::update()没有意义。

为什么不再做parent::update()一次而不是$temp->parent::update();

您有两个名为的方法,update()如果您调用$this->update()它,它将从调用对象的对象中调用该方法。你可以做

parent::update();

这将在类中运行update()方法ObjectOne

于 2013-08-28T17:40:35.380 回答
0

您可以使用以下语法调用任何受保护的和公共的父方法

parent::method_name();

在您的情况下,这将是: parent::update();

于 2013-08-28T17:46:17.507 回答