In this tutorial, we will learn about Traits in PHP. The trait is similar to a class but It isn't permitted to instantiate a Trait on its own. Traits are mainly used to declare methods that can be used in multiple classes. PHP only supports a single level inheritance(means we can inherit one class from another). But with the help of Traits, we can use freely use methods in different class hierarchies.
In PHP we use
traitkeyword to declare a Trait.
Please check out the following example code to know the basic syntax of Trait.
<?php
trait TraitOne{
public function hello() {
echo "Hello User! ";
}
}
?>
Now we will see how to use Trait in class.
<?php
trait TraitOne{
public function hello() {
echo "Hello User! ";
}
}
trait TraitTwo{
public function bye() {
echo "Bye Bye! ";
}
}
class Example{
use TraitOne;
use TraitTwo;
}
$obj = new Example();
$obj->hello();
$obj->bye();
?>
Note! use keyword is used to access Trait in class.
Parvesh Sandila is a results-driven tech professional with 8+ years of experience in web and mobile development, leadership, and emerging technologies.
After completing his Master’s in Computer Applications (MCA), he began his journey as a programming mentor, guiding 100+ students and helping them build strong foundations in coding. In 2019, he founded Owlbuddy.com, a platform dedicated to providing free, high-quality programming tutorials for aspiring developers.
He then transitioned into a full-time programmer, where his hands-on expertise and problem-solving skills led him to grow into a Team Lead and Technical Project Manager, successfully delivering scalable web and mobile solutions. Today, he works with advanced technologies such as AI systems, RAG architectures, and modern digital solutions, while also collaborating through a strategic partnership with Technobae (UK) to build next-generation products.
