PHP

PHP Menu

PHP

Abstract Classes - PHP OOP

An abstract class is a class that cannot be instantiated. Abstract classes can define abstract methods, which are methods without any body, only a definition:

abstract class MyAbstractClass {
    abstract public function doSomething($a, $b);
}

Abstract classes should be extended by a child class which can then provide the implementation of these abstract methods. The following is an example of an implementation of the abstract class.

<?php
abstract class Person { public $name; // the constructor function is public by default public function __construct($name) { $this->name = $name; } abstract public function sayHello() : string; }
// Child classes class Student extends Person { // inherited from parent class , needs to be defined but should follow the same parameters public function sayHello() : string { return "Hello! I'm a student and my name is $this->name!"; } }
class Employee extends Person { // inherited from parent class , needs to be defined but should follow the same parameters public function sayHello() : string { return "Hi! I'm an employee and my name is $this->name!"; } }
// create instances of the child classes $std = new Student("Frank"); echo $std->sayHello(); echo "<br>"; $worker = new Employee("Mark"); echo $worker->sayHello();

Exercise

Create an abstract class named Fruit, with a constructor function that gets the name of the fruit and an abstract function, color, that prints the color of the fruit. Create 3 child classes extending the abstract class namely: Apple, Orange, Grape. In these child classes, define the color function so that it prints Apple is red for the Apple class, Orange is orange for the Orange class and Grape is purple for the Grape class.

<?php
<?php
abstract class Fruit { public $name; public function __construct($name) { $this->name = $name; } abstract public function color(); }
// Child classes class Apple extends Fruit { public function color(){ return "$this->name is red"; } }
class Orange extends Fruit { public function color(){ return "$this->name is orange"; } }
class Grape extends Fruit { public function color(){ return "$this->name is purple"; } }
$apple = new Apple('Apple'); $orange = new Orange('Orange'); $grape = new Grape('Grape'); echo $apple->color(); echo "<br>"; echo $orange->color(); echo "<br>"; echo $grape->color();
{ "test_output_contains": [ { "expected":"Apple is red", "error_message":"Sorry, wrong output." }, { "expected":"Orange is orange", "error_message":"Sorry, wrong output." }, { "expected":"Grape is purple", "error_message":"Sorry, wrong output." } ], "test_variable_exists": { "object":"$name", "error_message":"Have you declared <code>$name<\/code>?" }, "test_function_exists": { "object":"color", "error_message":"Did you create <code>color<\/code>?" }, "success_message":"Good job!", "error_message":"There is something wrong on your code." }

Introduction

PHP Basics

PHP Advance

PHP OOP

PHP Functions and Methods