How to use the power of inheritance with composition in php
Inheritance and composition are two most basic and powerful components of OOP. They both have pros and cons but composition offers more flexibility as it lets you change the behavior being composed at run-time. Anyway, I am not going to the detail discussion in this article.
Imagine the scenario, you want to use composition but treat it like inheritance e.g. call composed object's method in the same way as calling the methods of the parent class. Here is how you can do it PHP by using __call and __callStatic magic method.
public class Wheel{
public function turnLeft($howMuch){
//some code here
}
}?
public function Car{
$protect wheel;
public function __construct(Wheel $wheel)
{
$this->wheel = $wheel;
}
}?
Now let's suppose you want to call turnLeft method of Wheel with Car class.
$wheel = new Wheel;
car = new Car($wheel);
car->turnLeft(5);
We can do this by using PHP magic methods __call and __callStatic. Here is how.
Define __call magic method in Car class
public function __call($method, $parameters)
{
return call_user_func([$this->wheel, $method], $parameters);
}?
When you will call turnLeft method on you car class, as this method doesn't exist in this class, the __call magic method will be called. The __call magic method will call the required method of the Wheel class.
For static methods, we can have the same approach, we just have to implement the __callStatic magic method.
public function __callStatic($method, $parameters)
{
return call_user_func([$this->wheel, $method], $parameters);
}?
This is the most basic example but it can be handy in real world scenarios.
PHP Developer(Laravel framework) and Frontend designer at Internetesolutions.com
7 年i want to internship in php please call me.
Technical Team Lead specializing in Back End and Front End Development
8 年Great article.