0

Practical question about usage of inheritance in php. I'm pretty new to this.

The project I'm working on encloses a.o. multiple charts which are all built up from data out of a database.

I've created multiple php classes. One class 'Filters' is inherited by all other classes. Filters connects to the DB and calculated and holds all arrays of selected filters and participants and the corresponding data.

2 classes, one class which creates the page Headers and one class which creates the Selectboxes, are used on each individual page (also inherits from Filters). And each individual page uses a class which creates a specific chart, which also inherits and uses a lot of variables from Filters. So each chart-page uses Filters + Header + Selectboxes + 'SpecificChart', the last 3 Classes inherit from Filters.

It all works perfectly. But because php does not support multiple inheritance, I created a function addFilters() to copy all necessary variables to use in the different classes, so I do not have to instantiate Filters multiple times.. I instantiate Filters and pass the object filters to the constructors of the other classes which call addFilters().

I was wondering if there's a better solution to this? Without the need to copy all the variables several times? I hope my explanation is clear..;)

  • Now you have very strong dependencies between all those classes. Why don’t you pass the Filters as an argument to the using classes? Read about Composition vs Inheritance. – fuxia Nov 20 '13 at 09:57
  • Thank you. I already pass the filter-object as an argument. But I think you mean I could store the object as an protected variable? Than I have to use $this->__filters->__'variable', right? I think the code would become pretty hard to read.. – user2182429 Nov 20 '13 at 13:20
  • Have a look at Traits: http://php.net/manual/en/language.oop5.traits.php – Dave Nov 20 '13 at 18:21

0 Answers0