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.
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
)
*/
?>
An Interface allows you to create programs that specifies which methods a class must implement, without defining how those methods are implemented.
A PHP class that has minimum one abstract method is called as abstract class and cannot be instantiated by itself.
Magic Methods are special types of methods in PHP that allows you to perform certain special actions. These methods start with a double underscore (__).