Interesting inheritance details in PHP5

From: Berislav Lopac (berislav.lopac_at_lopsica.com)
Date: 01/31/05


Date: Mon, 31 Jan 2005 15:02:21 +0100

Consider this code:

<?php
class TestClass
{
    private function TestMethod()
    {
        echo 1;
    }

    public function TestMe()
    {
        $this->TestMethod();
    }
}

class ExtendedTestClass extends TestClass
{
    private function TestMethod()
    {
        echo 2;
    }

}

$test1 = new TestClass();
$test2 = new ExtendedTestClass();

$test1->TestMe();
$test2->TestMe();

?>

Guess what be the output of this code?

I was testing the compliance of PHP5 to the Open-Closed principle, and found
out this strange behavior. In other words, you can override a private
function in a subclass, but if the calling method is declared only in the
superclass and not overriden in subclass, it will still call the original,
superclass's method, instead of the subclass's... Very strange -- or am I
missing something?

berislav