support@codebucket.net

What Is A Trait in PHP

What Is A Trait in PHP

K. M. Shawkat Zamil | January 18, 2023

Hello Developers,

 

In this demonstration, you will learn about traits in PHP. As you know, PHP does not support multiple inheritances. To solve this drawback, PHP comes up with traits.

 

What Is Traits

 

Traits are used to declare methods that can be used in multiple classes. Traits allow you to create desirable methods in a class setting, using the trait keyword. You can then inherit this class through the use keyword. 

 

Declare And Use Traits

 

To declare traits, you need to add a trait keyword like below:

 

<?php

  trait TraitName {
      // some code...
}

?>

 

To access a trait in your class, use the keyword used.

 

<?php

class MyClass {
    use TraitName;
}

?>

 

Let's look at an example:

 

<?php

trait city{
public function state() {
    echo "This is a state";
  }
}

class Country{
    use city;
}

$obj = new Country();
$obj->state();

?>

 

Here, we declare one trait: city. Then, we create a class: Country. The class uses the trait, and all the methods in the trait will be available in the class.

If other classes need to use the state() function, simply use the city trait in those classes. This reduces code duplication because there is no need to redeclare the same method over and over again. This is the beauty of a trait.

 

Let's look at an example of multiple traits:

 

<?php

trait city{
public function state() {
    echo "This is a state";
  }
}

trait region{
public function area() {
    echo "This is an area";
  }
}

class Country{
    use city;
}

class Zone{
    use city, region;
}


$obj = new Country();
$obj->state();

echo "<br>";
echo "<br>";

$obj1 = new Zone();
$obj1->state();
$obj1->area();

?>

 

Here, we declare two traits: city, and region. Then, we create two classes: Country, and Zone. Zone class uses two traits, and all the methods in the trait will be available in the class. We can use multiple traits with a comma.

 

Hope you enjoy it. This might help you in the journey of development.

 

Read More: How To Add A Countdown Timer In A Flutter Project

 

 

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.