How to create abstract classes and methods

An abstract class with an abstract method

abstract class Person { 
  private $firstName, $lastName, $phone, $email;

  // The constructor and the get and set methods are the same as the Person class

  // An abstract method 
  abstract public function getFullName();
}

A concrete class that implements an abstract class

class Customer extends Person {
  private $cardNumber, $cardType;

  public function __construct($first, $last, $phone, $email) {
    $this->setPhone($phone);
    $this->setEmail($email);
    parent::__construct($first, $last);
  } 
  
  public function getCardNumber() {
    return $this->cardNumber; 
  } 
  
  public function setCardNumber($value) {
    $this->cardNumber = $value; 
  } 
  
  public function getCardType() {
    return $this->cardType; 
  }
  
  public function setCardType($value) { 
    $this->cardType = $value; 
  } 
  
  // Concrete implementation of the abstract method 
  public function getFullName() {
    return $this->getFirstName() . ' ' . $this->getLastName(); 
  } 
}

Code that attempts to create an object from the abstract class

$customer = new Person('John', 'Doe'); // Fatal error

Code that creates and uses an object from the concrete

 class $customer = new Customer('John', 'Doe', '919-555-4321', 'jdoe@example.com');
 echo("<p>" .$customer->getFullName() . "</p>");

Description

Back