This site is mobile accessible. Press the "Tap Here" button to use a different font-size.
Smartphone icons created by Freepik - Flaticon
<?php
trait TraitName {
// some code...
}
?>
To use a trait in a class, use the
keyword:<?php
class MyClass {
use TraitName;
}
?>
Let's look at an example:
<?php trait message1 { public function msg1() { echo "OOP is fun! "; } } class Welcome { use message1; } $obj = new Welcome(); $obj->msg1(); ?>
Let's look at another example:
<?php trait message1 { public function msg1() { echo "OOP is fun! "; } } trait message2 { public function msg2() { echo "OOP reduces code duplication!"; } } class Welcome { use message1; } class Welcome2 { use message1, message2; } $obj = new Welcome(); $obj->msg1(); echo "<br>"; $obj2 = new Welcome2(); $obj2->msg1(); $obj2->msg2(); ?>
Here, we declare two traits: message1 and message2. Then, we create two classes: Welcome and Welcome2. The first class (Welcome) uses the message1 trait, and the second class (Welcome2) uses both message1 and message2 traits (multiple traits are separated by comma).
Eventually the navigation links, above, will be replaced by these (previous) and (next) buttons below.
Animated PHP icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon
Module 6 quiz