Doubts on inheritance and calling parent method

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
novito
Forum Commoner
Posts: 26
Joined: Mon Apr 07, 2008 11:08 am

Doubts on inheritance and calling parent method

Post 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 :)
User avatar
novito
Forum Commoner
Posts: 26
Joined: Mon Apr 07, 2008 11:08 am

Re: Doubts on inheritance and calling parent method

Post 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 :)
Post Reply