Inheritance in PHP

Inheritance:

Once you have a class, you can derive subclasses from it. This can save lots of painstaking code rewriting you can take class similar to the one you need to write, extend it to subclass, and just modify the parts that are different. you achieve this using the extends operator.
for example for Inheritance:

<?php
$object =new Subscriber;
$object->name="abhi";
$object->password="pword";
$object->phone="012 345 6789";
$object->email="[email protected]";
$object->display();
class User
{
public $name,$password;
function save_user()
{
echo "Save User code goes here";
}
}
class Subscriber extends User
{
public $phone,$email;
function display()
{
echo "Name: ".$this->name."<br>";
echo "Pass: ".$this->password."<br>";
echo "Phone: ".$this->phone."<br>";
echo "Email: ".$this->email;
}
}
?>
OUTPUT:
Name:abhi 
Pass:pword
Phone:012 345 6789
Email: [email protected]
2.Example for overriding a method and using the parent operators
<?php
$object=new Son;
$object->test();
$object->test2();
class Dad
{
function test()
{
echo "[Class Dad] I am your Father<br>";
}
}
class Son extends Dad
{
function test()
{
echo "[Class Son]I am Luke<br>";
}
function test2()
{
parent::test();
}
}
?>
OUTPUT:
[Class Son]I am  Luke
[Class Dad]I am your Father
Translate »