Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

PHP and Class Inheritance

Options
  • 03-05-2002 10:55am
    #1
    Registered Users Posts: 14,148 ✭✭✭✭


    Hey guys,

    just playing about with Classes and what-not in php. I've set up a base class and a derived class. The derived class appears to have no problems picking up inherited functions and such, but the values from the base class variables don't seem to be passed. here's the code:
    <?php
    
    class number1
    {
            var $a, $b, $c ;
    
            function number1()
            {
                    $this->a = 1 ;
                    $this->b = 4 ;
                    $this->c = 1 ;
                    $this->alpha = "More" ;
            }
    
            function add()
            {
                    $this->c = $this->a + $this->b ;
            }
    }
    
    class number2 extends number1
    {
            var $d ;
    
            function number2()
            {
                    $this->d = "Test" ;
            }
    
            function display()
            {
                    $this->add() ;
    
                    echo "a = ".$this->a."\n<br>\n" ;
                    echo "b = ".$this->b."\n<br>\n" ;
                    echo "c = ".$this->c."\n<br>\n" ;
                    echo $this->d."\n" ;
                    echo $this->more."\n" ;
            }
    }
    ?>
    <html>
    <head>
            <title>Inheritance Test</title>
    </head>
    
    <body>
            <?
                    $obj = new number2 ;
                    $obj->display() ;
            ?>
    </body>
    </html>
    

    And here's the output:
    a =
    b =
    c = 0
    Test


    Now, does the inherited object call both constructors (much like, say C++ does), or does the inherited constructor override the base class constructor??

    any ideas?


Comments

  • Registered Users Posts: 14,148 ✭✭✭✭Lemming


    Never mind .....

    RTFM Lemming :rolleyes:

    For anyone who read the above post and was wondering themselves:
    from PHP Manual

    Neither PHP 3 nor PHP 4 call constructors of the base class automatically from a constructor of a derived class. It is your responsibility to propagate the call to constructors upstream where appropriate.

    So the derived class constructor would look like this:
    function number2()
            {
                    $this->number1() ;
                    $this->d = "Test" ;
            }
    


Advertisement