0

I want to accomplish the following, but I'm not sure how to do it:

class foo {
    function doSomething(){
        // do something
    }
}

class bar extends foo {
    function doSomething(){
        // do something AND DO SOMETHING ELSE, but just for class bar objects
    }
}

Is it possible to do this while still using the doSomething() method, or do I have to create a new method?

Edit: To clarify, I do not want to have to restate 'do something' in the inherited method, I just want to state it once in the foo->doSomething() method and then build upon it in child classes.

3 Answers 3

2

You did it right there. If you want to call doSomething() in foo, simply do this in bar:

function doSomething() {
    // do bar-specific things here
    parent::doSomething();
    // or here
}

And the restating a method you mention, is commonly referred to as overloading.

Sign up to request clarification or add additional context in comments.

Comments

1

You can do this using the parent keyword:

class bar extends foo {
    function doSomething(){
        parent::doSomething();
    }
}

Comments

0

When extending a class you can simply use $this->method() to use the parent-method, as you have not overwritten it. When you have overwritten it, the snippet will point to the new method. You can access the parent-method via parent::method() then.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.