PHP Basic Tutorial
MySQL Connection
PHP Advanced
An abstract class in PHP is a class that cannot be instantiated directly. This means you can't create objects straight from an abstract class.
An abstract class is a class that contains at least one abstract method and it does not have body. The body is provided by the subclass (inherited from).
An abstract class or method is defined with the abstract
keyword:
✔ Declared using the abstract
keyword.
✔ Cannot be instantiated directly.
✔ Can contain both abstract and regular methods.
✔ Child classes must implement all abstract methods.
abstract class ClassName { abstract public function methodName(); // Abstract method (must be implemented) public function regularMethod() { // Regular method (optional to override) } }
protected
, the child class method can be protected
or public
, but not private
.Let's look at an example:
Try it yourself
1. Vehicle
(Abstract Class)
brand
, speed
).startEngine()
(to be implemented by child classes). 2. Car
(Concrete Class)
Vehicle
and implements startEngine()
.3. Creating an Object
Car
is instantiated and methods are called.Let's look at another example where the abstract method has an argument:
Try it yourself
In this example, we'll define an abstract class Vehicle
with an abstract method startEngine($keyType)
, where:
$keyType
).Car
adds two optional parameters ($fuelLevel
, $engineMode
).Try it yourself