Bivek Singh Bivek Singh - 3 months ago 15
PHP Question

Why does calling of test() function of Foo class (which extends Bar class) returns result mixed from both classes?

It may sound silly, but I'm new in PHP. I was learning from the documentation about access specifiers when I came to this section.

class Bar {
public function __construct() {
echo "Bar::constructor<br />";
}
public function test() {
$this->PublicTest();
$this->PrivateTest();
$this->protectedTest();
}
public function PublicTest(){
echo "Bar::testPublic<br />";
}
private function PrivateTest() {
echo "Bar::testPrivate<br />";
}
protected function ProtectedTest() {
echo "Bar::testProtected<br />";
}
}

class Foo extends Bar {
public function __construct() {
echo "Foo::constructor<br />";
}
public function PublicTest() {
echo "Foo::testPublic<br />";
}
private function PrivateTest() {
echo "Foo::testPrivate<br />";
}
protected function ProtectedTest() {
echo "Foo::testProtected<br />";
}
}

$myFoo = new Foo();
$myFoo->test();


?>

This produces output as:

Foo::constructor
Foo::testPublic
Bar::testPrivate
Foo::testProtected


Why does it prints from
Bar
class for
private
function while it prints from
Foo
class for
public
and
protected
function? Since, i don't have
test()
function in
Foo
class, it accesses the
test()
function from
Bar
class.

Where does
$this
pointer point to? Does it point to the function of
Foo
class or functions of
Bar
class? I'm really confused here. Can someone please explain this to me? Any help would be so much appreciated.

Answer

That's because of the visibility of each class/function. When we call test() at first, using this:

$myFoo = new Foo();
$myFoo->test();

We call the test() inside Bar class, since Foo extends Bar and it uses test() of Bar because it's public and is visible in class Foo. Now, inside foo() of Bar class, these 3 functions are called:

$this->PublicTest();
$this->PrivateTest();
$this->protectedTest();

Here, we are inside Bar class right now and hence it can see PrivateTest() and ProtectedTest() of it's own class only. Because the visibility of these functions are set to Private and Protected. But in case of PublicTest(), it can see 2 functions. Because PublicTest() is set to Public visibility for both Foo and Bar class. Here, Public function of Bar class is chosen although Foo class has its own PublicTest() because of following reason:

Since, we are using $this handler, which always reference to the object currently being used (which is of Foo class in this case), it chooses PublicTest() of Foo class.