Using Traits in Traits
Traits, like classes, can also use other traits. Let's look at an example. Suppose we have this trait with two methods:
<?php
trait Trait1
{
private function method1()
{
return 1;
}
private function method2()
{
return 2;
}
}
?>
Suppose we also have another trait:
<?php
trait Trait2
{
private function method3()
{
return 3;
}
}
?>
Let's connect the trait Trait1
to the trait Trait2
:
<?php
trait Trait2
{
use Trait1; // using the first trait
private function method3()
{
return 3;
}
}
?>
After such a connection, it turns out that Trait2
will have not only its own methods but also the methods
of the trait Trait1
. Let's test this: create a
class Test
, connect the trait
Trait2
to it, and make sure that our class
will have methods from both the first trait
and the second:
<?php
class Test
{
use Trait2; // connecting the second trait
public function __construct()
{
echo $this->method1(); // method of the first trait
echo $this->method2(); // method of the first trait
echo $this->method3(); // method of the second trait
}
}
?>
Independently create the same traits
as I have and connect them to the class Test
.
Create a method getSum
in this class,
returning the sum of the results of the methods of the connected
traits.