Skip to content

Instantly share code, notes, and snippets.

@atakde
Created November 7, 2022 16:56
Show Gist options
  • Save atakde/1c5ad1a25b050d82bb7fc4b3a6ec9fa8 to your computer and use it in GitHub Desktop.
Save atakde/1c5ad1a25b050d82bb7fc4b3a6ec9fa8 to your computer and use it in GitHub Desktop.
Inheritance vs Composition with PHP
<?php
class View
{
public function render($name)
{
echo "Rendering view $name";
}
}
class ControllerWithInheritance extends View
{
public function index()
{
$this->render('index');
}
}
class ControllerWithComposition
{
private $view;
public function __construct(View $view)
{
$this->view = $view;
}
public function index()
{
$this->view->render('index');
}
}
$controllerWithInheritance = new ControllerWithInheritance();
$controllerWithInheritance->index();
$controllerWithComposition = new ControllerWithComposition(new View());
$controllerWithComposition->index();
// Output:
// Rendering view index
// Rendering view index
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment