Ben
Ben

Reputation: 11188

PHP overloading a function from a parent class

I have a thing which I thought should work, but it doesn't.

I have several Controller_## classes, they all extend from Controller_Core. Each Controller_##-class has a public function Save(). Now I figured that I want to perform some other general checking (addslashes for each $_POST-var) and thought if I add a public function Save() to the Controller_Core it would be executed by default because the ##-class extends from it. However, this is not the case.

My question; is it possible what I'm trying to achieve? Or am I mistaken by thinking this would ever work?

Upvotes: 0

Views: 1624

Answers (2)

JonG
JonG

Reputation: 859

Or you could apply refactoring to extract common behavior to your core class :

class Controller_Core {

    public function save() {
        if ( ! $this->_validateInfo() ) {

            return false;
        }

        return $this->_doSave();
    }

    protected function _validateInput() {
        //-- do stuff

        return true;
    }

    protected function _doSave() {
        //-- do stuff

        return true;
    }

}

You write the specific code in the children classes, as in :

class Controller_Extended extends Controller_Core {

    protected function _doSave() {

        //-- a new return
        return true;
    }
} 

Upvotes: 1

Borealid
Borealid

Reputation: 98459

Call parent::Save() in the subclass version of the method.

See http://php.net/manual/en/keyword.parent.php .

Upvotes: 5

Related Questions