Abstract classes and methods
<?php
abstract class Car {
// abstract classes can have properties
protected $tankVolume ;
// abstract classes can have non abstract methods
public function setTankVolume( $volume ) {
$this->tankVolume = $volume ;
}
// abstract method
abstract public function calcNumMilesOnFullTank() ;
}
// Create a class that inherits an abstract class
class Honda extends Car {
/*
Since we inherited abstract method we need
to define it in the child class by
adding code to the method's body
*/
public function calcNumMilesOnFullTank() {
return $miles = $this->tankVolume * 30 ;
}
}
// another class that inherits from an abstract class
class Toyota extends Car {
/*
Again, we inherited abstract method we need
to define it in the child class by
adding code to the method's body
*/
public function calcNumMilesOnFullTank() {
return $miles = $this->tankVolume * 33 ;
}
// this method only available to Toyota objects
public function getColor() {
return 'Red';
}
}
// Honda
$honda1 = new Honda() ;
$honda1->setTankVolume(10) ;
echo $honda1->calcNumMilesOnFullTank() ;
echo PHP_EOL ;
// Toyota
$toyota1 = new Toyota() ;
$toyota1->setTankVolume(10) ;
echo $toyota1->calcNumMilesOnFullTank() ;
echo PHP_EOL;
echo $toyota1->getColor() ;
echo PHP_EOL;
// Exercise
abstract class User {
protected $username;
abstract public function stateYourRole() ;
public function setUsername( $uname ) {
$this->username = $uname ;
}
public function getUsername () {
return $this->username . PHP_EOL ;
}
}
// Admin inherits from Abstract class
class Admin extends User {
// define the abstract method from parent
public function stateYourRole() {
return 'Admin Role' . PHP_EOL;
}
}
// Viewer class
class Viewer extends User {
public function stateYourRole() {
return 'Viewer Role' . PHP_EOL ;
}
}
// Admin
$admin1 = new Admin() ;
$admin1->setUsername('Baphomet');
echo $admin1->stateYourRole() ;
echo $admin1->getUsername() ;
// Viewer
$viewer1 = new Viewer() ;
$viewer1->setUsername('Charlize Theron') ;
echo $viewer1->stateYourRole();
echo $viewer1->getUsername() ;