Traits - PHP - P62

Опубликовано: 14 Март 2026
на канале: Dino Cajic
391
15

There is a fundamental problem in programming languages that support Multiple Inheritance. PHP is not one of those languages, but let’s walk through it anyways just so that you understand the issue.

Assume there is a parent class that contains a specific method, such as drive. There are two children classes, class 1 and 2, and they each extend the parent class. They inherit the drive method and they override it.

Now, PHP doesn’t support what I’m about to tell you since this is a multiple inheritance issue. Another class, class 3, extends both class 1 and class 2. How does it know which drive method to use? Which method will it be inheriting? The one from class 1 or the one from class 2.

So that’s the multiple inheritance problem. There are times when you should extend from more than one class. So far, we can implement multiple methods, but we can’t extend the functionality of multiple classes. Traits are there to solve this issue. Just like abstract classes, you can’t instantiate Traits, but you can inherit them.

Read the full article on my website
https://www.dinocajic.com/php-traits/

Code for this tutorial
https://github.com/dinocajic/php-7-yo...

Full Code
https://github.com/dinocajic/php-7-yo...

PHP Playlist
   • PHP Tutorial  

--
Dino Cajic
Author and Head of IT

Homepage: https://www.dinocajic.com
GitHub: https://github.com/dinocajic
Medium:   / dinocajic  
Instagram:   / think.dino  
LinkedIn:   / dinocajic  
Twitter:   / dino_cajic  

My Books
An Illustrative Introduction to Algorithms
https://www.amazon.com/dp/1686863268

Laravel Excel: Using Laravel to Import Data
https://amzn.to/4925ylw

Code Along With Me - PHP: From Basic to Advanced PHP Techniques
https://amzn.to/3M6tlGN