Rodolfo Bandeira

Rodolfo Bandeira

software, electronics, security, devops, thoughts

How to load multiple classes in just one instance using PHP 5

As you already know, PHP like other languages just accept simple inheritance and not multiple inheritance. Today at work I had to create a class that saw three other classes and return all methods in just one instance. Actually what I really wanted was wrap all these three classes in just one. So, I had to figure out how to create a kind of multiple inheritance using PHP 5.

Dependency Injection

Look at this simple example below. We have some classes with a specific method each. The last class will access all methods and make it accessible using just one instance. We’re kind of simulating something like “class C extends A,B”

Here we can demonstrate the concept with a simple, yet naive example.

<?php

class A {
    public function test_a() { 
        echo "test_a! \n"; 
    }
}

class B {
    public function test_b() { 
        echo "test_b! \n"; 
    }
}

class MyFinalClass {
    // Passing class through the constructor method 
    // is called Dependency Injection
    public function __construct(A $myA, B $myB) {
        $this->a = $myA;
        $this->b = $myB;
    }
    public function test_a(){
        return $this->a->test_a();
    }
    public function test_b(){
        return $this->b->test_b();
    }
}

$final_instance = new MyFinalClass(new A, new B);
$final_instance->test_b();
$final_instance->test_a();

?>

Last modified:

LinkedIn
WhatsApp