Jump to content

OO inheritance


valdemark

Recommended Posts

Hey there!

 

First, please excuse me if someone have already asked the same question or if the problem is described in the tutorials/manual pages - I wasn't able to really find the answer anywhere and that's why I'm posting it here.

 

It is rather a simple OO related question. I have the following code:

 

<?php

class one {

  function one(){
        echo "one<br>";
  }
}

class two extends one {

        function two(){
                echo "two<br>";
        }
}

$obj = new two();
?>

 

Since I'm used with Java, I somehow assumed that this would produce: "one, two" because class Two extends One and the constructor of One should be called. This however is not the case and instead of the expected result, just "two" is displayed.

 

The question is, how can I ensure that the constructor of the parent class has been executed?

 

Again, sorry if the question is stupid or has been already answered :)

 

Link to comment
Share on other sites

Yes in java when you create a instance for a child class then the constructor for parent will be call automatically.

 

But in PHP is not like that . it is calling the constructor for only requested class.

 

you can try this.

 

<?php

 

class one {

 

function one(){

echo "one<br>";

}

}

 

class two extends one {

 

function two(){

$this->one();

echo "two<br>";

}

}

 

$obj = new two();

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.