Classese: Inheritance

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Templeton Peck
Forum Commoner
Posts: 45
Joined: Sun May 11, 2003 7:51 pm

Classese: Inheritance

Post by Templeton Peck »

Can someone tell me whats wrong, correct what I did with my code.. i'm just trying out playing with classes. I want to know how I can get the second class to call the first ones function and print out the name from
get_name;

Code: Select all

<?php
class mammal_t
{
	function mammal_t()
	{
		
	}
	
	function set_name($name)
	{
		$this->name = $name;
	}
	
	function get_name()
	{
		return $this->name;
	}
	
	var $name;
	
}

class human_t extends mammal_t
{
	function human_t()
	{
	}
	
	function get_name()
	{
		mammal_t::get_name();

	}
	
}


$human = new human_t();
$mammal = new mammal_t();

$mammal->set_name("smith");

echo $human->get_name();


?>
mod_edit: added php tags
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

you're creating two instances

Code: Select all

$human = new human_t();
$mammal = new mammal_t();
both are (more or less) independent from each other, so there is $human->name and $mammal->name.
After $mammal->set_name("smith"); $mammal->name is equal to smith, $human->name is not, because it hasn't been set.

try

Code: Select all

<?php
class mammal_t
{
	 var $name;
   function mammal_t()
   {
      
   }
   
   function set_name($name)
   {
      $this->name = $name;
   }
   
   function get_name()
   {
      return $this->name;
   }
}

class human_t extends mammal_t
{
   function human_t()
   {
   }
   
   function get_name()
   {
      // return the parent's return value
      return parent::get_name(); 
   }
   
}


$humanA = new human_t();
$humanB = new human_t();
$mammalA = new mammal_t();
$mammalB = new mammal_t();

$humanA->set_name('humanA');
$humanB->set_name('humanB');
$mammalA->set_name("mammalA");
$mammalB->set_name("mammalB");

echo $humanA->get_name(), "\n";
echo $humanB->get_name(), "\n";
echo $mammalA->get_name(), "\n";
echo $mammalB->get_name(), "\n";
?>
User avatar
Templeton Peck
Forum Commoner
Posts: 45
Joined: Sun May 11, 2003 7:51 pm

Post by Templeton Peck »

Thank you :)

i'm starting to get a decent understanding now
Post Reply