Page 1 of 1

Classese: Inheritance

Posted: Fri May 23, 2003 4:25 pm
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

Posted: Fri May 23, 2003 5:23 pm
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";
?>

Posted: Fri May 23, 2003 7:22 pm
by Templeton Peck
Thank you :)

i'm starting to get a decent understanding now