level0
level0

Reputation: 343

Visibility in PHP? context of `$this` when inherited?

I am new to php and I was going through the documentation for the visibility. I am little confused with this example in the documentation. when the call to $myFoo->test() is made, shouldn't it make a call to Foos $this->testPrivate(); . I mean shouldn't $this be Foos Object rather than Bar object? . As per my knowledge(I might be wrong here) Foo will have kind of its own test() method which is inherited from Bar and calling $myFoo->test() will make a call to '$this->testPrivate' where the $this should be Foos object myFoo. so How is it calling Bar's testPrivate method?

class Bar 
{
public function test() {
    $this->testPrivate();
    $this->testPublic();
}

public function testPublic() {
    echo "Bar::testPublic\n";
}

private function testPrivate() {
    echo "Bar::testPrivate\n";
}
}

class Foo extends Bar 
{
public function testPublic() {
    echo "Foo::testPublic\n";
}

private function testPrivate() {
    echo "Foo::testPrivate\n";
}
}

$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate 
            // Foo::testPublic
?>

Upvotes: 1

Views: 100

Answers (1)

Mark Baker
Mark Baker

Reputation: 212522

test() is in Bar, and will call the highest-level methods that Bar has access to. It has access to Foo's testPublic (because it is public) so it can call that, but it doesn't have access to Foo's testPrivate() (because it's private to Foo) so it calls it's own testPrivate() instead

Upvotes: 5

Related Questions