Viralscripts
                                 Viral Scripts
Empowering Your Mind, One Script at a Time.

Blog Full Detail

How to Inherit base class by super class in PHP ?

To inherit a base class by super class in PHP, you use the extends keyword. For example, the following code shows how to inherit the Animal class by the Dog class:

PHP

class Animal {
    protected $name;

    public function __construct($name) {
        $this-andgt;name = $name;
    }

    public function getName() {
        return $this-andgt;name;
    }
}

class Dog extends Animal {
    public function bark() {
        echo andquot;Woof!andquot;;
    }
}

Use code with caution.andnbsp;Learn more

content_copy

The Dog class now inherits all of the properties and methods of the Animal class. This means that a Dog object can access the name property and call the getName() method of the Animal class.

In addition, the Dog class can also override any of the properties and methods of the Animal class. For example, the following code shows how to override the getName() method of the Animal class to return a different value:

PHP

class Dog extends Animal {
    public function getName() {
        return andquot;My dogand#39;s name is andquot; . $this-andgt;name;
    }
}

Use code with caution.andnbsp;Learn more

content_copy

Now, when a Dog object calls the getName() method, it will return the string andquot;My dogand#39;s name is andquot; followed by the name of the dog.

Inheritance is a powerful feature of PHP that allows you to reuse code and create more complex and specialized classes.

Here are some additional things to keep in mind about inheritance in PHP:

  • Only public and protected properties and methods are inherited by subclasses. Private properties and methods are not inherited.
  • A subclass can override any public or protected property or method of its parent class.
  • A subclass cannot override a private property or method of its parent class.
  • A subclass can extend another subclass.