×
☰ See All Chapters

PHP Traits

PHP does not support multiple inheritance, you cannot inherit from multiple classes. A class can extend only one class. Through interfaces you can implement multiple inheritance partially, however here you have provide implementation for multiple interfaces.  Suppose you have to inherit already implemented features from multiple classes you have a solution from traits. Traits are used to declare methods that can be used in multiple classes. Traits can have concrete functions and abstract functions that can be used in multiple classes, and the functions can have any access modifier (public, private, or protected).

Syntax to declare trait

trait TraitName {

    // trait body

}

Syntax to use trait

class ClassName {

    use TraitName1, TraitName2...;

}

Trait Example

<?php

trait Apple {

    public function fruit1() {

        echo "I am Apple";

    }

}

 

trait Mango {

    public function fruit2() {

        echo "I am Mango";

    }

}

 

class Fruits {

    use Apple, Mango ;

}

 

class AppleFruit {

    use Apple;

}

 

$obj = new Fruits();

$obj->fruit1();

echo "<br>";

$obj->fruit2();

echo "<br>";

 

$obj2 = new AppleFruit();

$obj2->fruit1();

?>

php-traits-0


All Chapters
Author