Sobes.tech
Junior — Middle

How can you bypass or eliminate the difficulties associated with inheritance in PHP?

sobes.tech AI

Answer from AI

Inheritance issues in PHP are often related to the limitations of single inheritance and problems with code reuse. To overcome or mitigate these, the following are used:

  • Traits — a mechanism for code reuse that allows including methods from multiple sources into a class without inheritance.
  • Interfaces — to define contracts that classes must implement, increasing architectural flexibility.
  • Composition — instead of inheritance, a class contains objects of other classes and delegates tasks to them.

Example of using a trait:

trait Logger {
    public function log($msg) {
        echo "Log: $msg";
    }
}

class User {
    use Logger;
}

$user = new User();
$user->log('User created');