Abstract classes in PHP are used to extend other classes. Used when more then one class use the same logic. Good for readability and for hiding smaller (obvious) details to make our life simpler.
For example
Lets say we have a webshop with 2 types of Users: customers and employees. A User, no matter if it's a customer or employee, always has a user name
and user type
. Although the type differs per user, the name is always the same: user name. This is how our abstract class would look like:
<?php
abstract class User {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getUserName() {
return $this->name;
}
public abstract function getUserType();
}
But this abstract class on it's own won't do so much. If you would create an User object, you would have a non-functional user. This doesn't exist on our webshop. So in order to make it useful, we create our two types of users:
<?php
class Customer extends User{
private $id
public function __construct($name, $id) {
$this->name = $name;
$this->id = $id;
}
public function getUserType() {
return 'customer';
}
}
class Employee extends User{
private $id
public function __construct($name, $id) {
$this->name = $name;
$this->id = $id;
}
public function getUserType() {
return 'employee';
}
}
As you can see, these classes are extended from our abstract class. This means the getUserName() method is included/reachable, although not visual in our child classes.
Also every method written in the parent abstract class can be overwritten in the child class. As you can see we defined getUserType(), but without any functionally yet. In the child classes we overwrite this method and give it functionality. This now will tell us more about the type of the user being used.
Result
Now we can create our first customer and employee and output each user type.
$customer = new Customer('John', 1);
$employee = new Employee('Jane', 1);
echo 'John is a '. $customer->getUserType().'.';
echo '<br>';
echo 'Jane is a '. $employee->getUserType().'.';
This would output:
John is a customer.
Jane is a employee.
~That's all folks!
Top comments (1)
Short and sweet, I like it! When I first encountered abstract classes, I had interfaces thrown at me at the same time. I was trying to understand this while polymorphism came running for my legs. All the while inheritance and composition stood by and laughed at me 😬
All I'm trying to say is, bite-sized tutorials like these are pretty good for newcomers (and I've got some demons to slay 😄).