Traits in PHP

Hi all, today we will learn about “traits in php”. As we know, PHP is a single inheritance language i.e. a class defined in PHP can’t inherit more than one class. “Traits” are introduced to solve this problem.

What are Traits?

“A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way.” source php.net

Trait is just like a helper class which group reusable code.

It helps to follow DRY (Don’t Repeat Yourself).

You cannot instantiate a Trait on its own.

Trait vs Interface

When we use Interface then the class which is implementing have to implement all the method but in Trait we can define many function and can use a few. In trait, we can give definitions of a function for ex. a function can perform some task and return value.

Example

Let’s create two files main.class.php and child.class.php where child class inherits main class.

main.class.php

1

2

3

4

5

6

7

8

9

10

11

12

13

<?php

/**

* main.class.php

*/

classMain

{

functionshowMessage()

{

echo"Hi from parent class ".__METHOD__;

}

}

?>

child.class.php

1

2

3

4

5

6

7

8

9

10

<?php

include__DIR__.DIRECTORY_SEPARATOR.'main.class.php';

/**

* child.class.php

*/

classChildextendsMain

{

}

?>

Now we will create a trait file to use in child class, so let’s create a trait file as message.trait.php

message.trait.php

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<?php

/**

* message.trait.php

*/

traitMessage{

publicfunctionshowMessage()

{

echo'Hi friends you are learning traits in php';

}

publicfunctionsum($num1,$num2)

{

$sum=$num1+$num2;

return'Method called '.__METHOD__.' Sum of '.$num1.' and '.$num2.' is '.$sum;

}

}

?>

Now let’s create an object of child class and call showMessage method and get output as follows

“Hi from parent class Main::showMessage”

Now, to use trait we have to include file in child and use keyword “use” and updated file look as follows.

child.class.php

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<?php

include __DIR__.DIRECTORY_SEPARATOR.'main.class.php';

include __DIR__.DIRECTORY_SEPARATOR.'message.trait.php';

/**

* child.class.php

*/

classChildextendsMain

{

useMessage;

publicfunctionsum($num1,$num2)

{

$sum=$num1+$num2;

return'Method called '.__METHOD__.' Sum of '.$num1.' and '.$num2.' is '.$sum;

}

}

Create object of child class and call method showMessage and you can see output as follows

“Hi friends you are learning traits in php” which comes from showMessage function from trait.

Now create an object and call method sum with params 1 and 2 and you will get output as follows:

“Method called Child::sum Sum of 1 and 2 is 3” i.e. we can easily override trait function.

That’s it from traits, hope it will be a great add-on in your next project.