Page 1 of 1

Doubts on inheritance and calling parent method

Posted: Sat Aug 07, 2010 10:11 am
by novito
Hi there,

I have a doubt regarding to inheritance and calling a parent method from an extended class: The code is:

Code: Select all

<?php
	class person {
		var $name;
			function __construct($persons_name){
				$this->name = "Person".$persons_name;
			}
			function set_name($new_name){
				$this->name = "Person".$new_name;
			}
			function get_name(){
				return $this->name;
			}
	}
	class employee extends person {
		function __construct($persons_name){
			$this->name = "Employee".$persons_name;
		}
		function set_name($new_name){
			$this->name = "Employee".$new_name;
		}
		function get_name(){
			parent::get_name();
		}
	}

	?>
As you can see, I'm trying to access the get_name method from the extended class, and therefore I am expecting to return it's employee name when doing:

Code: Select all

$employed_man = new employee("Man Employed");
		echo $employed_man->get_name();
But this is not working.

Shouldn't this work? I tried to make an echo "testing"; inside get_name, and it does the echo, so I supposed is related with the $this variable, but I am not sure.

Some help?

Appreciate :)

Re: Doubts on inheritance and calling parent method

Posted: Sat Aug 07, 2010 11:32 am
by novito
I "fixed" what was wrong:

You have to add a return before the parent::get_name();, because the base class is returning the value to the extended class, but the extended class has to return it from the function too.

I hope this helps someone :)