PHP - Abstract Classes
Abstract classes are classes that contain one or more abstract methods.
An abstract method is a method that is declared, but not implemented in the code. Subclasses of the abstract class must implement all of the abstract methods in order to be instantiated. Abstract classes cannot be instantiated, and they are often used as a base class for other classes to extend from.
Syntax
<?php
abstract class BaseClass {
abstract public function someMethod1();
abstract public function someMethod2($name, $color);
abstract public function someMethod3() : string;
}
?>
Sample Code
<?php
// Base class
abstract class Car {
public $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function intro() : string;
}
// Derived classes
class Audi extends Car {
public function intro() : string {
return "Choose German quality! I'm an $this->name!";
}
}
class Volvo extends Car {
public function intro() : string {
return "Proud to be Swedish! I'm a $this->name!";
}
}
class Citroen extends Car {
public function intro() : string {
return "French extravagance! I'm a $this->name!";
}
}
// Create objects from the derived classes
$audi = new audi("Audi");
echo $audi->intro();
echo "<br>";
$volvo = new volvo("Volvo");
echo $volvo->intro();
echo "<br>";
$citroen = new citroen("Citroen");
echo $citroen->intro();
?>
Output
Choose Indian quality! I'm an Tata!
Proud to be a Korean! I'm a Kia!
British extravagance! I'm a MG!
Related Searches to Abstract Classes in PHP - PHP OOPs Abstract Class
php oop abstract classes
class abstraction
abstract classes in php
php oops abstract class
abstract classes and methods in php
php abstract class
explain abstract class in php
php abstract class and methods
php oop abstact classes and methods
php abstract classes
php abstract method
php abstract class constructor
php abstract class properties
interface class in php
abstract class in php with example