Tomáš Zato
Tomáš Zato

Reputation: 53149

How should I avoid the need for multiple class inheritance

I happened to need to extend my class from two others:

  1. My PDOUser class that provides basic PDO helper functions like getRow, query, mysql_error and so on.
  2. My Debuggable class, that provides debugging methods and error methods to print out nice debug and error messages.

I was taught that inheriting multiple classes is a confusing way to make programs and that's why PHP doesn't support it.

Why I wouldn't dare to doubt the advices of more experienced programmers, I can't see a way to solve my problem nicer.

I can't make any of the classes static. The PDOUser class provides protected property pdo that can be also accessed from child classes. The debugger class accesses the current classes names and method names to provide useful debug info.

I could make one of the helper classes inherit the other, but I think that would be confusing as well.

Upvotes: 2

Views: 1006

Answers (1)

Amir Popovich
Amir Popovich

Reputation: 29836

You can use composition over inheritance. This decouples yours objects. Your new class doesn't need to inherit two classes, it can hold them as instances and use their functionality.

Inheritance vs. Composition:

Upvotes: 2

Related Questions