codescracker


php

PHP Inheritance



« Previous Tutorial Next Tutorial »


When a class is defined by inheriting the existing function of a parent class then it is called inheritance.

Inheritance in PHP allows a class to inherit members from another class within same PHP program.

PHP Inheritance Example

Let's take a simple example on inheritance in PHP.

<!DOCTYPE html>
<html>
<head>
	<title>Inheritance Example in PHP</title>
</head>
<body>
<?php
	class Myclass
	{
		public function displaying_function($argument_vl)
		{
			echo "Output :<b>".$argument_vl."</b><hr/>";
		}
		public function displaying_function_alone()
		{
			echo "This is PHP Inheritance Tutorial with Example<hr/>";
		}
	}
	class Anotherclass extends Myclass
	{
		public function displaying_function($argument_vl)
		{
			echo "Another Output: <b>".$argument_vl."</b><hr/>";
		}
	}
	$obj1 = new Myclass();
	$obj2 = new Anotherclass;
	$obj1->displaying_function('I am an argument value passed in displaying function in Myclass class');
	$obj1->displaying_function_alone();
	$obj2->displaying_function("I am also an argument value passed in displaying function but in Anotherclass class");
	$obj2->displaying_function_alone();
?>
</body>
</html>

Below is the sample output of the above inheritance example

inheritance example php

Here is another example which will demonstrates inheritance in PHP.

<!DOCTYPE html>
<html>
<head>
	<title>Inheritance Example in PHP</title>
</head>
<body>
<?php
	class Like
	{
		public $whatILike;
		public function tellWhatULike()
		{
			return "I just like to read ".$this->whatILike." on CodesCracker";
		}
	}
	class LikeAnother extends Like
	{
		public function tellWhatULike()
		{
			return "I just like to read ".$this->whatILike." on CodesCracker";
		}
	}
	$objectLikeAnother = new LikeAnother();
	echo $objectLikeAnother->tellWhatULike();
	echo "<br/>";
	
	$objectLikeAnother = new LikeAnother();
	$objectLikeAnother->whatILike = "C++";
	echo $objectLikeAnother->tellWhatULike();
	echo "<br/>";
	
	$objectLike = new Like();
	echo $objectLike->tellWhatULike();
	echo "<br/>";
	
	$objectLike = new LikeAnother();
	$objectLike->whatILike = "PHP";
	echo $objectLike->tellWhatULike();
	echo "<br/>";
?>
</body>
</html>

Here is the sample output of the above example code on inheritance in PHP.

php inheritance

« Previous Tutorial Next Tutorial »




Tools
Calculator

Quick Links
Signup - Login - Give Online Test