Object composition in PHP with Example
Today we going to explore what is Class and Object in PHP and how to use it.
What is Object composition?
Object composition, To break it down into the simplest of terms, composition is when one object holds a pointer to another object.
This allows us to construct complex functionality by combining various types.
Let’s see some code example of object composition
class Subscription
{
protected $getway;
public function __construct(Getway $getway)
{
$this->getway = $getway;
}
public function create()
{
}
public function cancel()
{
return $this->getway->findCustomer();
}
public function invoice()
{
}
public function swap($newPlan)
{
}
}
interface Getway
{
public function findCustomer();
public function findSubscriptionByCustomer();
}
class StripeGetway implements Getway
{
public function findCustomer()
{
return 'Stripe Customer';
}
public function findSubscriptionByCustomer()
{
//
}
}
class BrainTreeGetway implements Getway
{
public function findCustomer()
{
return 'Braintree Customer';
}
public function findSubscriptionByCustomer()
{
//
}
}
echo (new Subscription(new StripeGetway))->cancel();
Object composition in PHP, as well as in many other object-oriented programming languages, is a design principle that allows you to create complex objects by combining or composing simpler objects. It is an alternative to inheritance, which is another way to create complex objects by inheriting properties and methods from parent classes.
For more details of OOP (Object Ordinated Programming) , you may have a look at the link given below. Feel free to leave a comment if you have any feedback or questions.
https://github.com/mohasin-dev/Object-Oriented-Programming-in-PHP
Bonus: You must love my most read article : How To Use Single Responsibility Principle in PHP/Laravel
And most GitHub star repo:
https://github.com/mohasinhossain/SOLID-Principles-in-PHP