Web Development Handbook

Web Development Handbook

Development is fun in a funny way

Traits: A way of code reuse in PHP
PHP

Traits: A way of code reuse in PHP

0 votes
0 votes
0 comments
192 views
Share

By Nihar Ranjan Das, Published on May 8th 2023 | 2 mins, 195 words

We all know PHP is a single inheritance language means we can inherit only one class. But sometimes we need to inherit multiple classes. PHP introduced Traits to overcome this problem in PHP 5.4.

To learn about inheritance in PHP, check out this.


Trait

In PHP, Trait is similar to a class in that it can contain methods, but it cannot be instantiated directly. Traits are designed to reduce code duplication by allowing you to reuse sets of methods in multiple classes.

Syntax

To create a trait:

<?php
trait Foo
{
    public static function hello()
    {            
       echo 'Hello World';      
    }
}

To use a trait:

<?php
class Bar
{
    use Foo;
}
var_dump(Bar::hello()); // Hello World

Let’s describe the code briefly and understand line by line.

In the code provided, there is a trait named "Foo". Inside the trait, there is a static method named "hello()" defined using the public static keywords. This method simply outputs the string "Hello World" using the echo statement.

Next, there is a class named "Bar". The class "Bar" uses the trait "Foo" with the use keyword. This means that the methods defined in the trait "Foo" can now be accessed within the class "Bar".


If you like our tutorial, do make sure to support us by buy us a coffee ☕️

Comments

Default avatar

Are you interested to learn more?

Be notified on future content. Never spam.