Google News
logo
PHP program to Abstract Classes
In the following example of PHP program that demonstrates the use of abstract classes :
Program :
<?php

// Define an abstract class 'Animal'
abstract class Animal {
    protected $name;

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

    // Define an abstract method 'speak'
    abstract public function speak();
}

// Define a class 'Cat' that extends 'Animal'
class Cat extends Animal {
    public function speak() {
        return "Meow";
    }
}

// Define a class 'Dog' that extends 'Animal'
class Dog extends Animal {
    public function speak() {
        return "Woof";
    }
}

// Create objects of the classes and call their 'speak' methods
$cat = new Cat("Fluffy");
$dog = new Dog("Buddy");

echo $cat->speak() . "<br>";  // Output: Meow
echo $dog->speak();  // Output: Woof
?>
In this program, we have defined an abstract class `Animal` with a constructor method that initializes the `$name` property and an abstract method `speak()`. The `speak()` method is defined as abstract, so any class that extends `Animal` must implement its own version of the `speak()` method.

We then define two classes `Cat` and `Dog` that extend `Animal` and implement their own `speak()` methods. Finally, we create objects of the `Cat` and `Dog` classes and call their `speak()` methods.
Output :
Meow
Woof​
In this way, we can use abstract classes to define common properties and behaviors that must be implemented by any class that extends them.