Sobes.tech
Junior — Middle

How do you apply the concept of inheritance in your projects?

sobes.tech AI

Answer from AI

Inheritance in PHP projects is used to create class hierarchies, where child classes extend the functionality of base classes. This allows for code reuse and simplifies maintenance. For example, you can create a base class User with common methods, and then inherit from it classes like Admin and Customer, adding specific methods for each.

class User {
    protected $name;
    public function __construct($name) {
        $this->name = $name;
    }
    public function getName() {
        return $this->name;
    }
}

class Admin extends User {
    public function accessAdminPanel() {
        return "Access to admin panel granted";
    }
}

$admin = new Admin('Ivan');
echo $admin->getName(); // Ivan
echo $admin->accessAdminPanel();

This approach helps structure the code and avoid duplication.