PHP OOP Traits Explained

Last Updated: 24 Jul, 2024

What is a Trait in PHP?

Traits in PHP, are a way of introducing code reuse. As we know PHP supports only single inheritance, traits are very helpful for us and reduce the limitations by allowing us to reuse sets of functions freely in several independent classes. A trait is very much similar to class, but it is used to group functionalities in a very organized way. We cannot instantiate a trait by itself.

Points to note:

  • Trait is created using trait keyword and you cannot instantiate a triat.
  • Trait reduces code complexity and solves the problems that are associated with multiple inheritance.
  • Trait declares methods and also defines the actual implementation for each of those methods.
  • Trait can define both static methods and static properties.
  • Trait allows you to reuse it's methods with freedom in various independent classes in totally different class hierarchies.
  • Trait cannot implements the interfaces, but it does support the use of abstract methods.
  • Traits are useful when various different indepndent classes share the same functionality.
  • Traits are injected in any class using use keyword.

When any class extends another class, following rules need to be followed:

  • A parent class inherited member is overridden by the trait member.
  • An inherited member from trait is overridden by the child class member, so it also overrides the parent class member as well.

Example 1: Below example shows the basic implementation of traits and has two methods to calculate sum and product of 2 numbers

<?php
trait CalculatorTrait
{
    public function calculateSum($a, $b)
    {
        return $a + $b;
    }
    public function calculateProduct($a, $b)
    {
        return $a * $b;
    }
}
class MyClass
{
    use CalculatorTrait;
}
$x = 10;
$y = 20;
$obj = new MyClass();
$sum = $obj->calculateSum($x, $y);
$product = $obj->calculateProduct($x, $y);
$details = array(
    'Sum' => $sum,
    'Product' => $product
);
print_r($details);
/* OUTPUT
Array
(
    [Sum] => 30
    [Product] => 200
)
*/
?>

Example 2: Below example shows the implementation of multiple traits inside class

<?php
trait CalculatorTrait
{
    public function calculateSum($a, $b, $c)
    {
        return $a + $b + $c;
    }
    public function calculateProduct($a, $b, $c)
    {
        return $a * $b * $c;
    }
}
trait OutputTrait
{
    public function printOutput($details)
    {
        print_r($details);
    }
}
class MyClass
{
    use CalculatorTrait, OutputTrait;
}
$x = 10;
$y = 20;
$z = 30;
$obj = new MyClass();
$sum = $obj->calculateSum($x, $y, $z);
$product = $obj->calculateProduct($x, $y, $z);
$details = array(
    'X' => $x,
    'Y' => $y,
    'Z' => $z,
    'Sum' => $sum,
    'Product' => $product
);
$obj->printOutput($details);
/* OUTPUT
Array
(
    [X] => 10
    [Y] => 20
    [Z] => 30
    [Sum] => 60
    [Product] => 6000
)
*/
?>

Example 3: Traits can also have abstract methods as shown in the below example

<?php
trait CalculatorTrait
{
    public function calculateSum($a, $b, $c)
    {
        return $a + $b + $c;
    }
    abstract function calculateProduct($a, $b, $c): int;
}
trait OutputTrait
{
    public function printOutput($details)
    {
        print_r($details);
    }
}
class MyClass
{
    use CalculatorTrait, OutputTrait;
    public function calculateProduct($a, $b, $c): int
    {
        return $a * $b * $c;
    }
}
$x = 10;
$y = 20;
$z = 30;
$obj = new MyClass();
$sum = $obj->calculateSum($x, $y, $z);
$product = $obj->calculateProduct($x, $y, $z);
$details = array(
    'X' => $x,
    'Y' => $y,
    'Z' => $z,
    'Sum' => $sum,
    'Product' => $product,
);
$obj->printOutput($details);
/* OUTPUT
Array
(
    [X] => 10
    [Y] => 20
    [Z] => 30
    [Sum] => 60
    [Product] => 6000
)
*/
?>

 

Thank You, Please Share.

Recommended Posts

IMAGE

PHP OOP Interfaces Explained

An Interface allows you to create programs that specifies which methods a class must implement, without defining how those methods are implemented.

IMAGE

PHP OOP Abstract Classes Explained

A PHP class that has minimum one abstract method is called as abstract class and cannot be instantiated by itself.

IMAGE

PHP Magic Methods Explained

Magic Methods are special types of methods in PHP that allows you to perform certain special actions. These methods start with a double underscore (__).