Create a class as “Percentage” with two properties length & width.
Calculate area of rectangle for two objects.
<?php
class Percentage
public $length;
public $width;
public $a;
function area($l,$w)
$this->length=$l;
$this->width=$w;
$this->a=$this->length*$this->width;
echo "Area of rectangle = " . $this->a;
$p1=new Percentage();
$p1->area(2,3);
$p2=new Percentage();
$p2->area(5,6);
?>
Inheritance:
1. It is the process of inheriting (sharing) properties and methods of base class
in its child class.
2. Inheritance provides reusability of code in a program.
3. PHP uses extends keyword to establish relationship between two classes.
4. Syntax :
class derived_class_name extends base_class_name
Class body
- derived_class_name is the name of new class which is also known as child class.
- base_class_name is the name of existing class which is also known as parent
class.
5. A derived class can access properties of base class and also can have its own
properties.
6. Properties defined as public in base class can be accessed inside as well as
outside of the class but properties defined as protected in base class can be
accessed only inside its derived class.
7. Private members of class cannot be inherited.
8. Example :
<?php
class college //BASE CLASS
public $name="ABC College";
protected $code=7;
class student extends college // derived class
public $sname="s-xyz";
public function display()
echo "College name=" .$this->name;
echo "<br>College code=" .$this->code;
echo "<br>Student name=" .$this->sname;
$s1=new student ();
$s1->display ();
?>