Search⌘ K
AI Features

Solution Review: Polymorphism

Learn how to implement polymorphism in PHP by creating abstract classes and methods, extending classes, and overriding methods. This lesson helps you understand how to design flexible, reusable code through inheritance and method overriding, demonstrated with practical examples of managing user roles and calculating scores.

We'll cover the following...

Solution

PHP
<?php
abstract class User {
protected $scores = 0;
protected $numberOfArticles = 0;
public function setNumberOfArticles($int) {
$numberOfArticles = (int)$int;
$this -> numberOfArticles = $numberOfArticles;
}
public function getNumberOfArticles() {
return $this -> numberOfArticles;
}
abstract public function calcScores();
}
class Author extends User {
public function calcScores() {
return $this -> scores = $this -> numberOfArticles * 10 + 20;
}
}
class Editor extends User {
public function calcScores() {
return $this -> scores = $this -> numberOfArticles * 6 + 15;
}
}
function test()
{
$author1 = new Author();
$author1 -> setNumberOfArticles(8);
$editor1 = new Editor();
$editor1 -> setNumberOfArticles(15);
return "Author score is " . $author1 -> calcScores(). " and Editor score is " . $editor1 -> calcScores();
}
echo test();
?>

Explanation

  • Line 2: We create a User class with protected properties named $scores and $numberOfArticles.
  • Line 6: We create setNumberOfArticles() setter method.
  • Line 10:
...