Traits in PHP. Code examples open

Traits in PHP. Code examples

Traits are a group of methods that can be added to classes. These classes are functional blocks that are repeatedly used in classes.
Traits are defined with a keyword trait:

trait Paint{

}

Traits can be filled with static and non-static methods:

trait Printer
{
    public function printSimpleText($text) { echo "$text<br>"; }
    public function printHeaderText($text) { echo "<h2>$text<h2>"; }
}

To insert trait you need add the “use” keyword

class Message
{
    use Printer;
}

//now we can use the trait method
$Message = new Message();
$Message->printSimpleText("Hello World!");

!when inherited, the trait methods override inherited methods with the same name:

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation