Advertisement
Google Ad Slot: content-top
PHP OOP - Traits
PHP - What are Traits?
- A trait is a way to reuse methods across multiple classes without using inheritance.
- Unlike abstract classes, traits do not require class extension.
- PHP does not support multiple inheritance, but traits allow multiple classes to share functionality.
- Traits are declared with the
traitkeyword:
Syntax:
<?php
trait TraitName {
// some code...
}
?>
To use a trait in a class, you use the use keyword inside the class definition.
Syntax:
<?php
class MyClass {
use TraitName;
}
?>
Let's look at an example:
Example
<?php
// Define a trait
trait MessageTrait {
public function showMessage() {
return "Hello from the trait!";
}
}
// Define a class that uses the trait
class MyClass {
use MessageTrait;
}
// Create an object of the class
$obj = new MyClass();
echo $obj->showMessage(); // Output: Hello from the trait!
?>
Explanation
- The
MessageTraittrait defines a methodshowMessage(). - The
MyClassuses theMessageTraitby using theusekeyword. - The
showMessage()method is available inMyClassand can be called on its object.
PHP - Using Multiple Traits
You can use multiple traits in a class by separating them with commas.
Let's look at another example:
Example
<?php
// First trait
trait Walk {
public function walk() {
return "I am walking!";
}
}
// Second trait
trait Speak {
public function sayHello() {
return "Hello, I am a " . get_class($this);
}
}
// Class using multiple traits
class Human {
use Walk, Speak;
}
$person = new Human();
echo $person->walk(); // Output: I am walking!
echo "<br>";
echo $person->sayHello(); // Output: Hello, I am a Human
?>
Explanation
WalkandSpeakare two separate traits, each with its own method.Humanuses both traits viause Walk, Speak;.$person(instance ofHuman) can access bothwalk()andsayHello()methods—trait methods are treated as if they belong to the class.