Friday 4 June 2021

Php: Traits

Traits allow developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

 

Unlike interfaces, traits can have methods with any visibility level.

 

Syntax

trait TraitName{

   

}

 

Example

trait Logger{

   

}

 

How to use a trait?

Syntax

use Trait_name;

 

Example

use Logger;

 

Find the below working application.

 

traits.php

#!/usr/bin/php

<?php

trait Logger{
    public function info($msg){
        $this->log($msg);
    }

    public function debug($msg){
        $this->log($msg);
    }

    public function error($msg){
        $this->log($msg);
    }

    private function log($msg){
        echo $msg;
    }
}

class MyClass{
    use Logger;
}

$obj = new MyClass();

$obj->debug("\nI am debug message\n");
$obj->info("I am information message\n");
$obj->error("I am error message\n");
?>

 

Output

$./traits.php 


I am debug message
I am information message
I am error message

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment