0

Is it possible in PHP 7 ?

Question: I have Parent class Foo. Bar class inherit from Foo and Bar2 class inherit from Foo and i want to inherit bar3 class from Bar and Bar2. Is it Possible ?

Image: enter image description here

this is possible in java (Diamond Inheritance) Java Example

how can i achieve this in PHP 7?

<?php

    class Foo
    {
        public function printItem()
        {
            echo 'Foo: ';
        }

    }

    class Bar extends Foo
    {
        public function printItem()
        {
            echo 'Bar: ';
        }
    }

    class Bar2 extends FOO
    {
        public function printItem()
        {
            echo 'Bar2';
        }
    }

    //class Bar3 extends Bar & Bar2 i need like this

    $foo = new Foo();
    $bar = new Bar();
    $bar2=new Bar2();
    $foo->printItem();
    $bar->printItem();
    $bar2->printItem();

    ?>

Sandbox link

Bilal Ahmed
  • 4,005
  • 3
  • 22
  • 42
  • 1
    It's not possible to do that in PHP, 7 or otherwise(at least the classical multiple inheritance). However, you can have a form of pseudo multiple inheritance by using [traits](http://php.net/manual/ro/language.oop5.traits.php). It's not ideal by any means, nor do I really recommend it. But if it's a constraint that you must workaround that this would be your best option as far as I know. – Andrei Oct 24 '17 at 07:28
  • @Andrew thanks your response. but i can't change or convert into trait the parent class. – Bilal Ahmed Oct 24 '17 at 07:32
  • You're stuck between a rock and hard place in that case. The only other workaround I, personally, can think of, is to inject the classes you need into the parent class. While clearly not inheritance, it will allow you to use the classes as part of the parent class. – Andrei Oct 24 '17 at 07:34
  • @Andrew yes i am stuck. ok i will try some other ways – Bilal Ahmed Oct 24 '17 at 07:39
  • It's not possible. Only way to get partial multiple sharing is to offload certain methods you need into Traits (http://php.net/manual/en/language.oop5.traits.php) – Gayan Hewa Oct 24 '17 at 09:02

0 Answers0