- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is traits in PHP?
In 5.4 PHP version trait is introduced to PHP object-oriented programming. A trait is like class however it is only for grouping methods in a fine-grained and reliable way. It isn't permitted to instantiate a trait on its own. Traits are introduced to PHP 5.4 to overcome the problems of single inheritance. As we know in single inheritance class can only inherit from one other single class. In the case of trait, it enables a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.
Example
<?php trait Reader{ public function add($var1,$var2){ return $var1+$var2; } } trait writer { public function multiplication($var1,$var2){ return $var1*$var2; } } class File { use Reader; use writer; public function calculate($var1,$var2){ echo "Ressult of addition:".$this->add($var1,$var2) ."
"; echo "Ressult of multiplication:".$this->multiplication($var1,$var2); } } $o = new File(); $o->calculate(5,3); ?>
Output
Result of addition two numbers:8 Result of multiplication of two numbers:15
Explanation
In the above example, we have implemented a function from two traits in a single class. Due to trait, we are able to access multiple functions in a single class.
Note
We are using the "USE" keyword to access traits inside a class.
- Related Articles
- PHP Traits
- Explain\"Dominant traits\".
- What is .htaccess in PHP?
- What are the Different Types of Consumer Personality Traits?
- Acquired and Inherited Traits
- What is header() function in PHP?
- What is explode() function in PHP?
- What is implode() function in PHP?
- What is Exception Handling in PHP ?
- What is method overloading in PHP?
- What is "namespace" keyword in PHP?
- What is Trailing Comma in PHP?
- From and Into Traits In Rust Programming
- How do traits get expressed?
- Personality Traits and Personality Types
