PHP OOP Abstract Classes

PHP Tutorial

 PHP OOP Abstract Classes

PHP OOP Abstract Classes

An abstract class is a class that cannot be instantiate (you cannot create objects from it).
It is used as a base/blueprint for other classes.


 Key Points About Abstract Classes

  •  You cannot create an object of an abstract class
  •  Abstract class may have abstract methods (no body)
  •  Child class must override abstract methods
  •  Can have normal methods also
  •  Supports properties & constructors
  • Supports protected & private members
  •  Supports inheritance

  Basic Abstract Class Example

You cannot do:

$animal = new Animal(); // ERROR

  Child Class Must Define Abstract Method


 


 Abstract Class with Normal Method


 


  Abstract Class with Constructor



 


  Multiple Abstract Methods


 


  Why Use Abstract Classes?

  •  Forces child classes to follow rules
  •  Ensures structure/pattern
  •  Useful when many classes share common behavior
  •  Helpful in large applications
  •  Used widely in frameworks like Laravel

Example: Laravel controller

All controllers extend it.


  Abstract Class vs Interface (Important)

FeatureAbstract ClassInterface
MethodsBoth normal + abstractOnly abstract (PHP 7), can have default in PHP 8
Constructor Yes No
Properties Yes (public only)
Multiple inheritance No Implement multiple interfaces
Use caseWhen base class is neededWhen only rules are needed

 Practical Example

Making a universal payment system:


 


 Summary (Easy to Remember)

ConceptMeaning
abstract classCannot make object, used as base
abstract methodMust be implemented by child
extendsChild inherits abstract class
PurposeEnforce structure in child classes

You may also like...