Exp 08
Exp 08
Resources required:
Hardware Software
Computer System Any database tools such as XAMPP
Practical Significance:
Inheritance:
Theoretical Background:
Inheritance:
To declare that one class inherits the code from another class, we use the extends
keyword.
Syntax :
class Parent
{
// The parent’s class code
}
class Child extends Parent
{
// The child can use the parent's class code
}
The child class can make use of all the non-private (public and protected) methods and
properties that it inherits from the parent class. This allows us to write the code only once in
the parent, and then use it in both the parent and the child classes.
class MyClass
{
function __construct()
{
echo “Welcome to PHP constructor. <br / > ”;
}
}
$obj = new MyClass; // Displays “Welcome to PHP constructor.”
Program Code:
a)
<?php
class Shape
{
public $length;
public $width;
public function __construct($length, $width)
{
$this->length = $length;
$this->width = $width;
}
}
class Rect extends Shape
{
public $height;
public function __construct($length, $width, $height)
{
$this->length = $length;
$this->width = $width;
$this->height = $height;
}
public function intro()
{
echo "The length is {$this->length}, the width is {$this->width}, and the height is {$this->height}
";
}
}
$r = new Rect(10,20,30);
$r->intro();
?>
b)
<?php
class Employee
{
public $name;
public $position;
function __construct($name,$position)
{
// This is initializing the class properties
$this->name=$name;
$this->profile=$position;
}
function show_details()
{
echo $this->name." : ";
echo "Your position is ".$this->profile."<br>";
}
}
Exercise:
1. Write a code to perform addition of 3 numbers using function.
2. Write a PHP program to check whether number is even or odd using function.
3. Write a PHP program to print factorial of number using function.
4. Write PHP program to calculate the sum of digits using function.
5. PHP program to check whether a number is prime or Not using function.