Web Development Handbook

Web Development Handbook

Development is fun in a funny way

What is PHP Abstract Classes? Advance OOP
PHP

What is PHP Abstract Classes? Advance OOP

0 votes
0 votes
0 comments
459 views
Share

By Nihar Ranjan Das, Published on May 15th 2023 | 9 mins, 866 words

PHP is a popular programming language used for web development. One of the advanced features of PHP is the concept of abstract classes. Abstract classes are classes that cannot be instantiated like Traits and are used as a blueprint for other classes to inherit from. In this article, we will discuss the basics of abstract classes in PHP and how to use them in your code.

What is a PHP Abstract Class?

PHP abstract class is a class that cannot be instantiated on its own. It is used as a base class for other classes to inherit from. Abstract classes are declared using the abstract keyword, and they can contain both abstract and non-abstract methods.

PHP Abstract classes are often used when you want to create a blueprint for a group of related classes. For example, if you are building a website that has different types of users, you could create an abstract User class that defines the basic properties and methods that all user types share. Then, you could create specific classes that inherit from the abstract User class and add additional properties and methods specific to that user type.

How to Define a PHP Abstract Class?

To define an abstract class in PHP, you use the abstract keyword before the class keyword, like this:

abstract class MyClass {
  // abstract and non-abstract methods and properties go here
}


Note that you cannot instantiate an abstract class directly, so you don't need to provide a constructor method.


Abstract methods are declared using the abstract keyword, and they must be implemented in any class that extends the abstract class. Here's an example:

abstract class Vehicle {
  abstract public function startEngine();
}


In this example, the Vehicle class is abstract, and it contains an abstract method called startEngine(). Any class that extends the Vehicle class must implement the startEngine() method.

How to Use a PHP Abstract Class?

To use an abstract class in your code, you must first create a new class that extends the abstract class. You can then add any additional methods or properties that are specific to your new class.

abstract class Vehicle {
  abstract public function startEngine();
}

class Car extends Vehicle {
  public function startEngine() {
    // code to start car engine goes here
  }
}


In this example, we've created a Car class that extends the abstract Vehicle class. The Car class must implement the startEngine() method, which it does by defining the code to start the car engine.

When to Use a PHP Abstract Class?

Abstract classes are useful when you want to define a set of properties and methods that are common to a group of related classes. By defining these common properties and methods in an abstract class, you can ensure that any class that inherits from the abstract class will have access to them.

Abstract classes are also useful when you want to enforce a particular set of methods that must be implemented by any class that inherits from the abstract class. This can help ensure that all of your classes have the same basic functionality and behavior.

Here's an example of how to use abstract classes in PHP for a data export application:

abstract class DataExporter {
    abstract public function exportData($data);
}

class CsvExporter extends DataExporter {
    public function exportData($data) {
        $filename = 'export-' . date('Ymd') . '.csv';
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        $output = fopen('php://output', 'w');
        fputcsv($output, array_keys($data[0]));
        foreach ($data as $row) {
            fputcsv($output, $row);
        }
        fclose($output);
    }
}

class ExcelExporter extends DataExporter {
    public function exportData($data) {
        $filename = 'export-' . date('Ymd') . '.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->fromArray($data, NULL, 'A1');
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save('php://output');
    }
}

// Example usage
$data = array(
    array('Name', 'Email', 'Phone'),
    array('John Doe', 'john@example.com', '123-456-7890'),
    array('Jane Smith', 'jane@example.com', '555-555-5555')
);

if ($_GET['export'] === 'csv') {
    $exporter = new CsvExporter();
} else {
    $exporter = new ExcelExporter();
}

$exporter->exportData($data);


In this example, we have an abstract class called DataExporter, which defines an abstract method called exportData(). Any class that extends DataExporter must implement the exportData() method.

We then have two classes that extend DataExporter: CsvExporter and ExcelExporter. These classes implement the exportData() method with their own logic for exporting data to a CSV file or an Excel spreadsheet.

Finally, we have an example usage of the DataExporter classes. Depending on the value of the export GET parameter, we create an instance of either CsvExporter or ExcelExporter and call the exportData() method with the data to export.

Conclusion

In summary, abstract classes are an advanced feature of PHP that allows you to define a set of properties and methods that are common to a group of related classes. Abstract classes cannot be instantiated directly, but they can be used as a base class for other classes to inherit from. When you use an abstract class, you can ensure that any class that inherits from it has access to a particular set of properties and methods, and you can also enforce a particular set of methods that must be implemented by any inheriting class.

If you like our tutorial, do make sure to support us by buy us a coffee ☕️

Comments

Default avatar

Are you interested to learn more?

Be notified on future content. Never spam.