1

I have two classes named RA_Shortcode and WPBakeryShortCodesContainer

Now I need a third class RA_ShortcodeContainer inherit both classes..

Any idea how to achieve it.

Thanks in advance

Shakeeb Ahmed
  • 1,778
  • 1
  • 21
  • 37
  • 1
    PHP doesn't allow multiple inheritance on a single class. You might want to look up Traits as a middle ground. – Jonnix Sep 01 '16 at 13:22
  • 1
    From the naming, I'd have expected a `WPBakeryShortCodesContainer` to contain a collection of `RA_Shortcode` records, likewise `RA_ShortcodeContainer` might extend `WPBakeryShortCodesContainer` (or vice versa) but can't see why a Container needs to extend the class that it's a container for – Mark Baker Sep 01 '16 at 13:31
  • WPBakeryShortCodesContainer is a 3rd party class and RA_Shortcode is ours which cut down our lines of code we are coding per project so same goes for RA_ShortcodeContainer and need major code from RA_Shortcode so I dont want to write them again in RA_ShortcodeContainer – Shakeeb Ahmed Sep 01 '16 at 13:34

2 Answers2

0

There is no current way to implement multiple inheritance with PHP. You can either use Traits to achieve what you are trying to accomplish or include the class(es) with require, include or use statements (or dependency injection). However, Traits seem like the best and most straight forward way to go.

John B
  • 159
  • 3
  • 14
  • Why do traits seem like the best way to go? What's so straight forward about using Traits? – dbf Sep 02 '16 at 07:50
  • @dbf - Since multiple inheritance is not possible using the ```extends``` method in PHP - the only real way to accomplish what the original author was trying to do (and with the least amount of code) is to use a Trait. The concept of a Trait is shareable code. From the PHP Docs: "Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies." – John B Sep 16 '16 at 15:24
  • example with code would clarify it more. – Istiaque Ahmed Oct 16 '17 at 14:38
0

The short answer is: you don't.


Based on your class names (btw, look up the concept of namespaces), there isn't even need for multiple inheritances.

When a class B inherits from class A, it means that class A is a specialized case of B.

Maybe this will illustrate your situation. Let's say you have a classes Box and Cat. And now you need a specialized BoxForCats class. The BoxForCats should never extend from Cat. Instead you should apply compositions.

Your RA_ShortcodeContainer class should just have:

public function addShortcode(RA_Shortcode $shortcode)
{
    $this->list[] = $shortcode;
}

P.S. read up about LSP

tereško
  • 58,060
  • 25
  • 98
  • 150