Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend multiple utility classes [duplicate]

Tags:

oop

php

This question is kinda aimed towards PHP but it probably applies to other languages aswell. In PHP you can only extend one class. But what if you need more classes?

Suppose i have the following classes:

class MyClass extends Observer, Logger, OtherUtilClass

MyClass can't extend more than one class. But it needs to be an observer. And it might need some other base class aswell to fully function. What would be the best approach for this?

like image 864
w00 Avatar asked Mar 22 '12 08:03

w00


People also ask

How do you extend from multiple classes?

In Java, we can extend two classes by using the “extend” keyword, which means that the child class will inherit all of the parent class's properties. Here, Child represents the child class, and Parent denotes the Parent class. Java supports single inheritance but not multi-inheritance.

Can an object extend multiple classes?

You can only Extend a single class. And implement Interfaces from many sources. Extending multiple classes is not available.

Can we extend multiple classes in JS?

In JavaScript we can only inherit from a single object. There can be only one [[Prototype]] for an object. And a class may extend only one other class.

How do I extend multiple classes in node JS?

Install the “extends-classes” Package By default, each class in Node. js can extend only a single class. That means, to inherit from multiple classes, you'd need to create a hierarchy of classes that extend each other.


2 Answers

No

Your idea leads to multiple inheritance and it is not available in PHP for good.

I extremely recommended you read this question to see why you shouldn't try this.


However, you still can chain the classes. If done in a proper way you can get the functionality of all classes.

Class Observer {}
Class Logger extends Observer {}
Class OtherUtilClasses extends Logger {}

//Now
class MyClass extends OtherUtilClasses {}
like image 81
Starx Avatar answered Sep 20 '22 11:09

Starx


In PHP 5.4, one class can use several traits.

like image 45
jpic Avatar answered Sep 20 '22 11:09

jpic