Introduction:
In this lesson we will Learn about abstract classes and methods in PHP Object-Oriented Programming (OOP) with a comprehensive guide ,practical examples and projects. Abstract classes support a blueprint for classes and methods without implementation details, enabling code reusability and maintaining a clear structure in OOP designs.
The Abstract classes in PHP are classes that cannot be instantiated directly. They are designed to be extended by other classes, serving as a blueprint for those subclasses.
The Abstract classes can include abstract methods, which are methods declared but not implemented in the abstract class. Subclasses that extend an abstract class must implement all the abstract methods declared in the parent abstract class.
The Abstract classes can also have regular methods with implementations.
abstract class Shape { protected $color; public function __construct($color = 'black') { $this->color = $color; } // Abstract method abstract public function calculateArea(); // Regular method public function getColor() { return $this->color; } } class Circle extends Shape { private $radius; public function __construct($radius, $color = 'black') { parent::__construct($color); $this->radius = $radius; } // Implementing abstract method public function calculateArea() { return pi() * $this->radius * $this->radius; } } class Rectangle extends Shape { private $width; private $height; public function __construct($width, $height, $color = 'black') { parent::__construct($color); $this->width = $width; $this->height = $height; } // Implementing abstract method public function calculateArea() { return $this->width * $this->height; } } // Attempting to instantiate an abstract class will result in an error // $shape = new Shape(); // This will throw an error // Instantiate subclasses $circle = new Circle(5, 'red'); $rectangle = new Rectangle(4, 6, 'blue'); // Calling methods echo "Circle Area: " . $circle->calculateArea() . "\n"; echo "Circle Color: " . $circle->getColor() . "\n"; echo "Rectangle Area: " . $rectangle->calculateArea() . "\n"; echo "Rectangle Color: " . $rectangle->getColor() . "\n";
In this example, Shape is an abstract class with one abstract method calculateArea() and one regular method getColor(). The Circle and Rectangle classes extend the Shape abstract class and support implementations for the abstract method calculateArea(). When creating instances of Circle and Rectangle, We can see how they inherit the properties and methods of the abstract class Shape.
Here’s a step-by-step how to use PHP OOP with abstract classes:
Start by defining Wer abstract class using the abstract keyword.
This class will contain properties and methods that serve as a blueprint for its subclasses.
abstract class Animal { protected $name; abstract public function makeSound(); }
The Abstract methods are methods declared in the abstract class but not implemented.
They must be implemented by any class that extends the abstract class.
abstract class Animal { protected $name; abstract public function makeSound(); }
Create concrete subclasses that extend the abstract class.
These subclasses must support implementations for all the abstract methods declared in the abstract class.
class Dog extends Animal { public function makeSound() { return "Woof!"; } } class Cat extends Animal { public function makeSound() { return "Meow!"; } }
We can instantiate objects of the concrete subclasses. Since the abstract class cannot be instantiated directly, We’ll always work with the concrete subclasses.
$dog = new Dog(); $cat = new Cat();
We can call methods on the objects as usual, including the abstract methods which have been implemented in the subclasses.
echo $dog->makeSound(); // Output: Woof! echo $cat->makeSound(); // Output: Meow!
We can also include non-abstract methods in the abstract class. These methods can have implementations and can be inherited by the subclasses.
abstract class Animal { protected $name; abstract public function makeSound(); public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } }
We’ve successfully used PHP OOP with the abstract classes.
The Abstract classes support a way to define a common interface for a group of subclasses while allowing individual subclasses to support their own implementations for certain methods.
Here is a complete PHP code example showing how to use PHP OOP with abstract classes in a web page:
<!DOCTYPE html> <html> <head> <title>PHP OOP - Abstract Classes Example</title> </head> <body> <?php // Define abstract class abstract class Shape { protected $color; public function __construct($color = 'black') { $this->color = $color; } // Abstract method abstract public function calculateArea(); // Regular method public function getColor() { return $this->color; } } // Define concrete subclasses class Circle extends Shape { private $radius; public function __construct($radius, $color = 'black') { parent::__construct($color); $this->radius = $radius; } // Implementing abstract method public function calculateArea() { return pi() * $this->radius * $this->radius; } } class Rectangle extends Shape { private $width; private $height; public function __construct($width, $height, $color = 'black') { parent::__construct($color); $this->width = $width; $this->height = $height; } // Implementing abstract method public function calculateArea() { return $this->width * $this->height; } } // Instantiate subclasses $circle = new Circle(5, 'red'); $rectangle = new Rectangle(4, 6, 'blue'); // Output results echo "<h2>Shape Calculations</h2>"; echo "<h3>Circle:</h3>"; echo "Area: " . $circle->calculateArea() . "<br>"; echo "Color: " . $circle->getColor() . "<br>"; echo "<h3>Rectangle:</h3>"; echo "Area: " . $rectangle->calculateArea() . "<br>"; echo "Color: " . $rectangle->getColor() . "<br>"; ?> </body> </html>
In this example, we have a web page that displays the areas and colors of a circle and a rectangle.
The classes Shape, Circle, and Rectangle show the use of abstract classes and inheritance.
The web page outputs the calculated areas and colors for each shape instantiated.
Here’s another complete example showing the use of PHP OOP with abstract classes in a web page.
In this example, we’ll create an abstract class Animal with abstract methods and concrete subclasses Dog and Cat:
<!DOCTYPE html> <html> <head> <title>PHP OOP - Abstract Classes Example</title> </head> <body> <?php // Define abstract class abstract class Animal { protected $name; public function __construct($name) { $this->name = $name; } // Abstract method abstract public function makeSound(); } // Define concrete subclasses class Dog extends Animal { // Implementing abstract method public function makeSound() { return "Woof!"; } } class Cat extends Animal { // Implementing abstract method public function makeSound() { return "Meow!"; } } // Instantiate subclasses $dog = new Dog("Buddy"); $cat = new Cat("Whiskers"); // Output results echo "<h2>Animal Sounds</h2>"; echo "<p>{$dog->name} says: " . $dog->makeSound() . "</p>"; echo "<p>{$cat->name} says: " . $cat->makeSound() . "</p>"; ?> </body> </html>
This example shows how abstract classes can define a common interface (in this case, the makeSound() method) that must be implemented by concrete subclasses.
In PHP, abstract classes and methods are features of object-oriented programming that allow We to define a blueprint for classes and methods without providing implementation details. Here’s a breakdown of each:
Abstract class is a class that cannot be instantiated directly. It serves as a template or blueprint for other classes to inherit from.
Abstract classes may contain a mix of concrete (implemented) methods and abstract (unimplemented) methods.
Abstract classes are defined using the abstract keyword.
Abstract classes can support a common interface and shared functionality to its subclasses while allowing each subclass to implement its own behavior.
Subclasses of an abstract class must either implement all the abstract methods defined in the parent abstract class or be declared as abstract themselves.
abstract class Animal { abstract public function makeSound(); }
An abstract method is a method declared in an abstract class but without providing an implementation.
Abstract methods are defined using the abstract keyword and must end with a semicolon instead of a method body.
Abstract methods serve as placeholders that must be implemented by any concrete subclass extending the abstract class.
Subclasses of an abstract class must support implementations for all the abstract methods declared in the parent abstract class.
Example of an abstract method in PHP:
abstract class Animal { abstract public function makeSound(); }
In summary, abstract classes and methods in PHP support a way to define common interfaces and behaviors that can be shared among multiple classes, promoting code reusability and maintaining a clear structure in object-oriented designs.
complete code in web page with explanation
Here is a complete PHP code example with explanations embedded in comments. This example shows the use of the abstract classes and methods in a web page context:
<!DOCTYPE html> <html> <head> <title>PHP OOP - Abstract Classes and Methods Example</title> </head> <body> <?php // Define an abstract class 'Animal' abstract class Animal { // Properties protected $name; // Constructor public function __construct($name) { $this->name = $name; } // Abstract method to be implemented by subclasses abstract public function makeSound(); } // Define a concrete subclass 'Dog' that extends 'Animal' class Dog extends Animal { // Implementing the abstract method 'makeSound' public function makeSound() { return "Woof!"; } } // Define another concrete subclass 'Cat' that extends 'Animal' class Cat extends Animal { // Implementing the abstract method 'makeSound' public function makeSound() { return "Meow!"; } } // Instantiate objects of the concrete subclasses $dog = new Dog("Buddy"); $cat = new Cat("Whiskers"); // Output the results echo "<h2>Animal Sounds</h2>"; echo "<p>{$dog->name} says: " . $dog->makeSound() . "</p>"; // Accessing the 'name' property of 'Dog' echo "<p>{$cat->name} says: " . $cat->makeSound() . "</p>"; // Accessing the 'name' property of 'Cat' ?> </body> </html>
Explanation:
We will go to create a complete PHP project that shows the use of abstract classes and methods. In this project, we’ll create a simple shape calculator that calculates the area of different geometric shapes (circle and rectangle) using abstract classes.
shape_calculator/
│
├── classes/
│ ├── Shape.php
│ ├── Circle.php
│ └── Rectangle.php
│
├── index.php
└── style.css
Explanation:
classes/: This directory will contain our PHP class files.
Shape.php: This file contains the abstract class Shape, which defines the blueprint for shape objects.
Circle.php: This file contains the concrete class Circle, which extends Shape and calculates the area of a circle.
Rectangle.php: This file contains the concrete class Rectangle, which extends Shape and calculates the area of a rectangle.
index.php: This is our main PHP file that displays a form to input shape dimensions and calculates the area based on the selected shape.
style.css: This file contains some basic CSS styles to improve the appearance of our web page.
<?php abstract class Shape { abstract public function calculateArea(); } ?>
<?php require_once 'Shape.php'; class Circle extends Shape { private $radius; public function __construct($radius) { $this->radius = $radius; } public function calculateArea() { return pi() * $this->radius * $this->radius; } } ?>
<?php require_once 'Shape.php'; class Rectangle extends Shape { private $width; private $height; public function __construct($width, $height) { $this->width = $width; $this->height = $height; } public function calculateArea() { return $this->width * $this->height; } } ?>
<!DOCTYPE html> <html> <head> <title>Shape Calculator</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div class="container"> <h1>Shape Calculator</h1> <form method="post"> <label for="shape">Select Shape:</label> <select name="shape" id="shape"> <option value="circle">Circle</option> <option value="rectangle">Rectangle</option> </select> <br><br> <div id="dimension"> <label for="dimension1">Enter Dimension 1:</label> <input type="number" name="dimension1" id="dimension1" required> <br><br> <label for="dimension2">Enter Dimension 2:</label> <input type="number" name="dimension2" id="dimension2" required> <br><br> </div> <input type="submit" value="Calculate"> </form> <div id="result"> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { require_once 'classes/Circle.php'; require_once 'classes/Rectangle.php'; if ($_POST['shape'] == 'circle') { $radius = $_POST['dimension1']; $circle = new Circle($radius); echo "<p>Area of Circle: " . $circle->calculateArea() . "</p>"; } elseif ($_POST['shape'] == 'rectangle') { $width = $_POST['dimension1']; $height = $_POST['dimension2']; $rectangle = new Rectangle($width, $height); echo "<p>Area of Rectangle: " . $rectangle->calculateArea() . "</p>"; } } ?> </div> </div> </body> </html>
.container { width: 400px; margin: 0 auto; text-align: center; margin-top: 50px; } h1 { color: #333; } label { font-weight: bold; } input[type="number"] { width: 200px; padding: 10px; margin-top: 5px; } input[type="submit"] { padding: 10px 20px; background-color: #007bff; color: white; border: none; cursor: pointer; margin-top: 10px; } input[type="submit"]:hover { background-color: #0056b3; } #result { margin-top: 20px; }
Explanation:
we will go to create another PHP project using abstract classes and methods.
In this project, we’ll implement a simple online store system with abstract classes for products and concrete subclasses for different types of products (books and electronics).
online_store/
│
├── classes/
│ ├── Product.php
│ ├── Book.php
│ └── Electronics.php
│
├── index.php
└── style.css
Explanation:
classes/: This directory will contain our PHP class files.
Product.php: This file contains the abstract class Product, which defines the blueprint for product objects.
Book.php: This file contains the concrete class Book, which extends Product and represents a book product.
Electronics.php: This file contains the concrete class Electronics, which extends Product and represents an electronics product.
index.php: This is our main PHP file that displays product information.
style.css: This file contains some basic CSS styles to improve the appearance of our web page.
Product.php
<?php abstract class Product { protected $name; protected $price; public function __construct($name, $price) { $this->name = $name; $this->price = $price; } abstract public function getDescription(); } ?>
Book.php
<?php require_once 'Product.php'; class Book extends Product { private $author; public function __construct($name, $price, $author) { parent::__construct($name, $price); $this->author = $author; } public function getDescription() { return "Book: {$this->name} by {$this->author}, Price: {$this->price}"; } } ?>
Electronics.php
<?php require_once 'Product.php'; class Electronics extends Product { private $brand; public function __construct($name, $price, $brand) { parent::__construct($name, $price); $this->brand = $brand; } public function getDescription() { return "Electronics: {$this->brand} {$this->name}, Price: {$this->price}"; } } ?>
index.php
<!DOCTYPE html> <html> <head> <title>Online Store</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div class="container"> <h1>Welcome to Our Online Store</h1> <div id="products"> <?php require_once 'classes/Book.php'; require_once 'classes/Electronics.php'; // Create book and electronics objects $book = new Book("The Great Gatsby", 10.99, "F. Scott Fitzgerald"); $electronics = new Electronics("Smartphone", 599.99, "Samsung"); // Display product descriptions echo "<p>{$book->getDescription()}</p>"; echo "<p>{$electronics->getDescription()}</p>"; ?> </div> </div> </body> </html>
style.css
.container { width: 600px; margin: 0 auto; text-align: center; margin-top: 50px; } h1 { color: #333; } #products { margin-top: 20px; } p { font-size: 18px; margin-bottom: 10px; }
Explanation:
Similar to the previous project, we have three PHP class files (Product.php, Book.php, Electronics.php) inside the classes/ directory. Product.php defines an abstract class Product, while Book.php and Electronics.php define concrete subclasses Book and Electronics respectively.
index.php is the main file that displays product information. It creates instances of Book and Electronics objects and displays their descriptions.
style.css contains basic styles to improve the appearance of the web page.
This project shows the use of abstract classes and methods in PHP to create a simple online store system. The abstract class Product defines a common interface for different types of products, while concrete subclasses Book and Electronics support specific implementations for book and electronics products, respectively.
To run this project, We’ll need a local development environment with PHP installed. We can follow these steps:
If We don’t have a local development environment set up, We can install software like XAMPP (for Windows, macOS, Linux) or MAMP (for macOS) that supports Apache, MySQL, and PHP stack.
Alternatively, We can install PHP and a web server like Apache or Nginx separately on Wer system.
Project Setup:
Create a directory named online_store in Wer web server’s document root directory.
Inside the online_store directory, create subdirectories named classes.
Create the PHP files (Product.php, Book.php, Electronics.php, index.php) and CSS file (style.css) as described in the project structure above.
Place the respective code content in each file according to the supportd examples.
Start Wer local web server (Apache or Nginx) and make sure it’s running.
Open a web browser and navigate to http://localhost/online_store/index.php (or whatever Wer local server’s URL and project directory structure are).
We should see the main page of the online store with product information displayed, including the book and electronics descriptions.
Interact with the Project:
We can modify the code in the PHP files (index.php, Product.php, Book.php, Electronics.php) to see how changes affect the output.
We can also add more product types by creating new concrete subclasses of Product and including them in the index.php file.
By following these steps, We can set up and run the PHP project showing the use of abstract classes and methods in an online store context
Multiple-choice quiz based on the lesson about PHP OOP – Abstract Classes:
a) A class that cannot be instantiated directly
b) A class with only abstract methods
c) A class that does not contain any properties
d) A class with static methods only
Correct Answer: a) A class that cannot be instantiated directly
Explanation: Abstract classes in PHP are classes that cannot be instantiated directly. They serve as templates or blueprints for other classes to inherit from.
a) final
b) abstract
c) class
d) extends
Correct Answer: b) abstract
Explanation: In PHP, the abstract keyword is used to define an abstract class.
a) A method that cannot be accessed from outside the class
b) A method that cannot be overridden in subclasses
c) A method without an implementation in the abstract class
d) A method that can only be called statically
Correct Answer: c) A method without an implementation in the abstract class
Explanation: An abstract method in PHP is a method declared in an abstract class without providing an implementation. Subclasses must implement these methods.
a) Abstract classes can be instantiated directly
b) Abstract classes can contain only abstract methods
c) Abstract classes cannot contain properties
d) Abstract classes support implementations for all methods
Correct Answer: b) Abstract classes can contain only abstract methods
Explanation: Abstract classes in PHP can contain a mix of abstract and concrete methods, but they must have at least one abstract method.
a) To prevent inheritance
b) To support a blueprint for subclasses
c) To make all methods private
d) To allow direct instantiation
Correct Answer: b) To support a blueprint for subclasses
Explanation: Abstract classes in PHP support a blueprint for subclasses to inherit from, allowing them to share common interface and functionality.
a) Abstract classes must contain only static methods
b) Abstract classes can be instantiated directly
c) Abstract classes can extend multiple classes
d) Abstract classes can have constructors
Correct Answer: d) Abstract classes can have constructors
Explanation: Abstract classes in PHP can have constructors just like regular classes.
a) static
b) final
c) abstract
d) public
Correct Answer: c) abstract
Explanation: In PHP, the abstract keyword is used to declare an abstract method.
a) The subclass inherits the implementation from the parent class
b) An error occurs
c) The abstract methods are automatically implemented
d) The subclass becomes abstract
Correct Answer: b) An error occurs
Explanation: If a subclass of an abstract class does not implement all abstract methods, a fatal error will occur.
a) Abstract methods must be declared with the public visibility modifier
b) Abstract methods cannot have parameters
c) Abstract methods must end with a semicolon
d) Abstract methods must be implemented by subclasses
Correct Answer: d) Abstract methods must be implemented by subclasses
Explanation: Abstract methods in PHP must be implemented by subclasses that extend the abstract class.
a) No, all methods in abstract classes must be abstract
b) Yes, abstract classes can have both abstract and concrete methods
c) No, abstract classes cannot contain any methods
d) Yes, but only if the concrete methods are declared as final
Correct Answer: b) Yes, abstract classes can have both abstract and concrete methods
Explanation: Abstract classes in PHP can contain both abstract and concrete methods, providing implementations for common functionality.