buley
buley

Reputation: 29208

Accessing parent methods in PHP

I've got a TopLevelClass that calls AnotherClass which has functions. From inside functions, how do you access some_other_methods() for TopLevelClass?

If it were JavaScript-esque my problem would look like:

$this->parent()->parent()->do_something()

and it would be equivalent to

$this_function->AnotherClass()->LevelClass()->some_other_methods()

Upvotes: 1

Views: 133

Answers (3)

foxsoup
foxsoup

Reputation: 306

You could make AnotherClass extend TopLevelClass with:

class AnotherClass extends TopLevelClass {
  // class stuff in here
}

This would give AnotherClass access to all the methods in TopLevelClass as well as it's own (subject to Private scope status).

Upvotes: 1

Dereleased
Dereleased

Reputation: 10087

if you are using proper inheritance, you just need the parent keyword.

class foo {
    protected function fooMethod() {}
}
class bar extends foo {
    public function barMethod() {
        parent::fooMethod();
        // technically, you could do the same thing with $this->fooMethod()
        // but this way you also know how to do it with methods that might have
        // the same name as one another, such as parent::__construct()
    }
}

Upvotes: 3

Harmen
Harmen

Reputation: 22438

Out the top of my head:

parent::some_other_methods();

Upvotes: 1

Related Questions