DEV Community

Pradeep Singh Rajpurohit
Pradeep Singh Rajpurohit

Posted on

Traits In PHP

PHP only supports single inheritance, but with the use of traits, we can achieve multiple inheritance.

A trait in PHP is like a set of reusable functions that you can add to different classes. It's a way to share code between classes without using regular inheritance.

Lets take an example:-

1. Declare Trait
We can declare a trait with the trait keyword:

<?php
trait Trait1 {
    public function method1() {
        echo "Method 1 from Trait1!";
    }
}

trait Trait2 {
    public function method2() {
        echo "Method 2 from Trait2!";
    }
}
?>
Enter fullscreen mode Exit fullscreen mode

Above we have declared two traits.

2. Use of Trait
To use a trait in a class, use the use keyword:

<?php
trait Trait1 {
    public function method1() {
        echo "Method 1 from Trait1!\n";
    }
}

trait Trait2 {
    public function method2() {
        echo "Method 2 from Trait2!\n";
    }
}

class MyClass {
    use Trait1, Trait2;
}

$obj = new MyClass();
$obj->method1(); // Output: Method 1 from Trait1!
$obj->method2(); // Output: Method 2 from Trait2!
?>
Enter fullscreen mode Exit fullscreen mode

I hope You understand the concept of traits.
Thank for Reading.

Top comments (2)

Collapse
 
sourovpal profile image
Sourov Pal

Hi,
This is Sourov Pal. I am a freelance web developer and Software Developer. I can do one of project for free. If you like my work you will pay me otherwise you don't need to pay. No upfront needed, no contract needed. If you want to outsource your work to me you may knock me.

My what's app no is: +8801919852044
Github Profile: github.com/sourovpal
Thanks

Collapse
 
mexikode profile image
MexiKode ⚙ • Edited
trait Trait1 {
    public function method1() {
        echo "PHP is Beautiful!\n";
    }
}

class MyClass {
    use Trait1;
}

$obj = new MyClass();
$obj->method1();
Enter fullscreen mode Exit fullscreen mode