Created
November 7, 2022 16:56
-
-
Save atakde/1c5ad1a25b050d82bb7fc4b3a6ec9fa8 to your computer and use it in GitHub Desktop.
Inheritance vs Composition with PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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