Using Traits in PHP

Introduction

In this article I will explain Traits in PHP. A trait is similar to a class and an abstract class. Traits are a new feature introduced by PHP 5.4 and is a very powerful feature in PHP 5.4 but this feature is not supported in prior versions of PHP. The traits mechanism enables code reuse in a single inheritance using PHP that cannot be instantiated on its own. Traits is one of the most significant additions for PHP. Traits are like horizontal code and are for reusing for common stuff like log-in, security, caching etcetera.

Example

Trait syntax looks like this:

<?php

class database extends Mysql

{

}

class Mysqli extends Mysql

{

}

?>

Example

This example shows precedence order in traits. An class inherited from the "abc" class is overridden by a member inserted by a trait.

<?php

class abc{

    public function helloabc()

       {

        echo 'hello ';

    }

}

trait helloMCN{

    public function helloabc()

       {

        parent::helloabc();

        echo 'MCN!';

    }

}

class MyhelloMCN extends abc

{

    use helloMCN;

}

$s = new MyhelloMCN();

$s->helloabc();

?>

 

Output


cal.jpg


Example

 

Example of an alternate precedence order in traits.

 

<?php

trait abc
{

    public function helloabc()
{

        echo 'hello MCN!';

    }

}

class helloisnotenough {

    use abc;

    public function helloabc() {

        echo 'hello csharpcorner!';

    }

}

$s = new helloisnotenough();

$s->helloabc();

?>

Output


cal1.jpg

 

Example

 

Example of multiple traits. Multiple traits allow you to insert into a class by listing them in the "use" statement and separated by the commas operator.

 

<?php

trait abc{

    public function helloabc()
 {

        echo 'hello ';

    }

}

trait xyz{

    public function helloxyz()
 {

        echo 'MCN';

    }

}

class myMCN {

    use abc, xyz;

    public function helloExclamation()
{

        echo '!';

    }

}

$s = new myMCN();

$s->sayabc();

$s->sayxyz();

$s->helloExclamation();

?>

Output

cal.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all