odannyc
odannyc

Reputation: 718

PHP: Access Method in sub-class

I want to know how to access a method i a sub-class of a class when I'm in another sub-class of that same class... For example:

class foo {

}

class bar extends foo {
    public function something() {
        //do something here
    }
}

class soap extends foo {
    $this->something();   //This is the method I wanna call...
}

As you can see I wanna access a subclass's method from another sub class. How do I do this in PHP?

Upvotes: 1

Views: 128

Answers (1)

Jeff Lambert
Jeff Lambert

Reputation: 24661

You can do it directly, but only if soap is also a subclass of bar:

class soap extends bar {
    public function someFunction() 
    {
        $this->something();   // This will work
    }
}

If it's not, you still have an option: obtain an instance of bar and then call the method on it:

class soap extends foo {
    public function someFunction(bar $bar) 
    {
        $bar->something();   // This will also work
    }
}

Barring that, there's not much else you can do. Since bar is not in soap's inheritance chain, there is no way to reference something using only $this from within any of soap's methods.

Upvotes: 3

Related Questions