How to inherit more than one class in PHP?

Asked

Viewed 1,502 times

2

There is the possibility of inheriting two classes in PHP?

I have a class that already inherits the class Usuarios and would like her to inherit the class Crud also.

class Alunos extends Usuarios {
}

4 answers

8

Can not, almost no language allows and even those that allow is problematic.

There is the possibility of using interfaces (see also) defining contracts and making a kind of multiple inheritance, subtype, but not subclass, so there’s no code reuse, or traits that does limited code reuse. It’s not the same as inheriting from a class, but it helps.

Anyway almost all the problems that one thinks one needs to inherit from more than one class is abusing the inheritance, and then it would be good for one to rethink all their understanding of inheritance, probably that person uses inheritance where it should not even in simple cases.

I think it’s weird one Aluno was one Usuario, may be, but it’s not common. Aluno certainly not a Crud. There I do not think that even simple inheritance fits. In fact neither composition between these two things would fit.

This is why I always repeat that almost every OOP code is wrong, in general has more confusion of concepts than solution to problems. I tell you what, if people start using OOP right they start quitting.

4


Prefer composition to inheritance.

You don’t need to inherit. Just instantiate the classes within it and use.

In PHP there is no support for multiple inheritances.

1

Or you could create an interface to encapsulate your code and implement through the Crud class, which the Usuarios class would extend and finally the students class would inherit its attributes and methods, you can instantiate without any problem.

interface Conexao { metodos();}

class Crud implements Conexao{herdaria metodo(){}} 

class Usuarios extends Crud{herdaria metodo(){}} 

class Alunos extends Usuarios{herdaria os metodos de ambas}

$aluno1 = new Alunos();

That would make it easier.

0

In PHP there is a feature called Traits. It is a programming method (shared by other languages as well) to add more functionality to a class.

If the goal is for several classes to use CRUD methods, it may be a good way out.

Link to the official documentation

An article by Imasters

Browser other questions tagged

You are not signed in. Login or sign up in order to post.