Object Oriented Programming(OOP) Series: Traits

Object Oriented Programming(OOP) Series: Traits

Traits in simple terms with examples

In this OOP concepts series using PHP, Javascript, and Dart we've covered Classes & Objects , Attributes & Methods, Constructor & Destructor, Access modifier, Inheritance, Polymorphism, Abstraction, Encapsulation, Namespaces

A trait is a distinguishing character.

Traits in the context of object-oriented programming are classes used to declare methods with any access modifier that can be used in multiple classes. It cannot be instantiated just like an interface but can be used within a class.

Trait in PHP

PHP doesn't support multiple inheritances but there are cases where for the purposes of reusing codes in several parts of an application trait comes into play.

For instance:

//this doesn't work

Class A extends B, C{
}

The keyword trait is used in PHP

<?php
trait Tutorial{
//write the methods with any access modifier
}
?>

The keyword use is used to access trait(s) within a class.

<?php
trait tutorial {
public function trait_message() {
    echo "I\'m a trait in PHP";
  }
}

class Introduction {
 //since trait is not a class we can only access it but can't instantiate it
  use tutorial;
}

$trait_obj = new Introduction();
$trait_obj->trait_message();
?>

image.png

Output

image.png

We can also access multiple traits from within a class and make use of their methods similar way shown above:

class Introduction {
  use tutorial, phptutorial;
}

In situations where there are conflicts of methods from different traits we can use an alias to differentiate the methods:

use tutorial, phptutorial{
        phptutorial::message as phpMessage;
    }

Traits in Javascript & Dart

There is no direct implementation of traits in Javascript and Darts as in the case of C#, PHP, or RUST.

However, there are approaches that are used to allow multiple methods to be used within a class.

Traitjs can be used in Javascript that supports trait behavior. This [article] (barbarianmeetscoding.com/blog/safer-javascr..) provides an example of the implementation

The essence of this tutorial is to explain the trait concepts.

Thank you for reading this article.

Stay tuned for the next article on the OOP Series: Dependency Injection

Please kindly share with your network and feel free to use the comment section for questions, answers, and contributions.

Do you love this article?? please follow me on hashnode or Twitter @alemsbaja to stay updated for more on this OOP series

Did you find this article valuable?

Support Alemoh Rapheal Baja by becoming a sponsor. Any amount is appreciated!