Php trait in Oops

In Php “trait” is a new concept which is introduced to achieved” multiple inheritence”. 

trait are created  using “trait” keyword followed by the name of “trait“.

you can define variables, methodsabstract methods in trait, you can define everything that you defined within a class definition.

you can also defined static properties and static methods within a trait.

“trait properties” and “functions” are accessible ” within a class”.

you can not create an “instance” of the “trait“.

we can use a trait (functionality)  within a class by using ” use ” keyword followed by the trait name.

you can use multiple trait in a class just by separating trait names by commas.

you can avoids conflict of methods by using traits.

If two trait have same method name then we called a method by using ” trait  “ name followed by “scope resolution operator(::)”  function name“insteadof”  ” trait name “( trait which have same function name ).

Example:


<?php

    trait Hello{
    
        public function sayhello(){
          echo "Hello";
        }
        
    }
    
    trait Everyone{
    
        public function sayhello(){
          echo "Everyone";
        }
        
    }
    
    trait HelloEveryone{
    
        use Hello,Everyone{
             Everyone :: sayHello&nbsp; insteadof&nbsp; Hello;
        }
        
    }

?>

Example 1:


<?php

    trait A{
    
        public $a = 10;
        public $b = 20;
        
        public function add(){
           return $this->a + $this->b;
        }
            
    }
    
    trait B{
    
        //some code here
    }
    
    class C{
    
        use A,B;
        
    }
    
    $obj = new C();
    echo $obj->a;
    echo"<br>";
    echo $obj->add();

?>

------------ ****** ------------

OUTPUT:
         10
		 30

Example 2:


<?php 

    trait Hello{
    
         public function sayHello(){
             echo"Hello";
        } 
    }
    
    trait Everyone{
    
        public static $x=10;
        
        public function sayHello(){
           echo"Everyone";
        }
        
        public static function sta_fun(){
           echo "Static method";
        }
        
        public abstract function abs();
    }
    
    trait HelloEveryone{
    
        use Hello,Everyone{
           Everyone::sayHello insteadof Hello;
        }
    }
    
    class HelloWorld{
    
        use HelloEveryone;
        
        public function sayWorld(){
            echo "World";
        }
        
        public function abs(){
            echo "abstract function of trait Everyone";
        }
    }
    
    $obj = new HelloWorld();
    
    $obj->sayHello();
    echo"<br>";
    
    $obj->sayWorld();
    echo"<br>";
    
    HelloWorld::sta_fun();
    echo"<br>";
    
    echo HelloWorld::$x;
    echo"<br>";
    
    $obj->abs();

?>

------------ ****** ------------

OUTPUT:
         Everyone
         World
		 
		 Static method
		 10
         abstract function of trait Everyone.