logo CBCE Skill INDIA

Welcome to CBCE Skill INDIA. An ISO 9001:2015 Certified Autonomous Body | Best Quality Computer and Skills Training Provider Organization. Established Under Indian Trust Act 1882, Govt. of India. Identity No. - IV-190200628, and registered under NITI Aayog Govt. of India. Identity No. - WB/2023/0344555. Also registered under Ministry of Micro, Small & Medium Enterprises - MSME (Govt. of India). Registration Number - UDYAM-WB-06-0031863

PHP Abstract Classes and Methods!


PHP Abstract Classes and Methods
 

In PHP, abstract classes and methods are used to create blueprints for classes. Abstract classes cannot be instantiated on their own; they serve as a foundation for other classes to inherit from. Abstract methods, on the other hand, are declared in abstract classes but have no implementation in the abstract class itself. Instead, the classes that extend the abstract class must provide an implementation for these abstract methods.

Here's a basic example to illustrate abstract classes and methods in PHP:

<?php

// Abstract class
abstract class Shape {
    // Abstract method
    abstract public function calculateArea();
    
    // Regular method
    public function getDescription() {
        return "This is a shape.";
    }
}

// Concrete class that extends the abstract class
class Circle extends Shape {
    private $radius;

    // Constructor
    public function __construct($radius) {
        $this->radius = $radius;
    }

    // Implementation of the abstract method
    public function calculateArea() {
        return pi() * $this->radius * $this->radius;
    }
}

// Concrete class that extends the abstract class
class Square extends Shape {
    private $side;

    // Constructor
    public function __construct($side) {
        $this->side = $side;
    }

    // Implementation of the abstract method
    public function calculateArea() {
        return $this->side * $this->side;
    }
}

// Instantiate objects
$circle = new Circle(5);
$square = new Square(4);

// Call methods
echo $circle->getDescription() . " Area: " . $circle->calculateArea() . "\n";
echo $square->getDescription() . " Area: " . $square->calculateArea() . "\n";

?>

In this example:

  • The Shape class is an abstract class with an abstract method calculateArea() and a regular method getDescription().
  • The Circle and Square classes extend the Shape class and provide implementations for the abstract method calculateArea().
  • Objects of the Circle and Square classes can be instantiated, and their methods can be called.

 

Abstract classes and methods are useful when you want to enforce a certain structure in the classes that inherit from them while allowing for variations in the implementation of specific methods.

 

Thank you.

Popular Post:

Give us your feedback!

Your email address will not be published. Required fields are marked *
0 Comments Write Comment