Search⌘ K
AI Features

Solution Review: Inheritance

Explore inheritance in PHP object-oriented programming by working with protected properties, creating subclasses, and overriding methods. Understand how to use magic constants like __CLASS__ and implement practical OOP features to manage user roles and interactions.

We'll cover the following...

Solution

PHP
<?php
class User {
protected $username;
public function setUsername($name) {
$this -> username = $name;
}
}
class Admin extends User {
public function expressYourRole() {
return strtolower(__CLASS__);
}
public function sayHello() {
return "Hello admin, " . $this -> username;
}
}
function test(){
$admin1 = new Admin();
$admin1 -> setUsername("Balthazar");
return $admin1 -> sayHello();
}
echo test();
?>

Explanation

-** Line 2:** We create a User class with a protected property named $username. The User class also contains a public setter method named setUsername(), which is used to set the value of the $username ...