Interesting inheritance details in PHP5

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Berislav Lopac

    Interesting inheritance details in PHP5

    Consider this code:

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

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

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

    }

    $test1 = new TestClass();
    $test2 = new ExtendedTestCla ss();

    $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


  • chernyshevsky@hotmail.com

    #2
    Re: Interesting inheritance details in PHP5

    A situation where you need to use "final," perhaps?

    Comment

    • Berislav Lopac

      #3
      Re: Interesting inheritance details in PHP5

      chernyshevsky@h otmail.com wrote:[color=blue]
      > A situation where you need to use "final," perhaps?[/color]

      Why? The idea is that PHP5 should either comply with the OCP (ie, allow
      private methods to be overriden, but not accessed), or not (not allow
      private methods to be neither overriden nor accessed). It however won't
      complain if you override it, but when you call it from another method it
      will depend on where the caller method is defined which method (original or
      overriden to call). AFAIK, this is contrary to all the OOP principles I
      know...

      Berislav


      Comment

      • chernyshevsky@hotmail.com

        #4
        Re: Interesting inheritance details in PHP5

        It follows the ISC principle--implement something on the cheap.

        Comment

        Working...