- Sebelumnya kita sudah tahu bahwa class bisa menggunakan trait lebih dari satu
- Lantas bagaimana dengan trait yang menggunakan trait lain?
- Trait bisa menggunakan trait lain, mirip seperti interface yang bisa implement interface lain
- Untuk menggunakan trait lain dari trait, penggunaanya sama seperti dengan pengunaan trait di class
<?php
namespace Data\Traits;
trait SayGoodBye
{
public string $name;
public function goodBye (?string $name): void
{
if (is_null($name)) {
echo "Good bye" . PHP_EOL;
} else {
echo "Good Bye $name" . PHP_EOL;
}
}
}
trait SayHello
{
public string $name;
public function hello (?string $name): void
{
if (is_null($name)) {
echo "Hello" . PHP_EOL;
} else {
echo "Hello $name" . PHP_EOL;
}
}
}
trait HashName
{
public string $name;
}
trait CanRun
{
public abstract function run(): void;
}
class ParentPerson
{
public function goodBye(?string $name): void
{
echo "Good by in Person" . PHP_EOL;
}
public function hello(?string $name): void
{
echo "Good bye in Person" . PHP_EOL;
}
}
//trait inheritance
trait all
{
use SayGoodBye, SayHello, HashName, CanRun{
//hello as private;
//goodBye as private;
}
}
class Person extends ParentPerson
{
use all;
public function run(): void
{
echo "Person $this->name is running" . PHP_EOL;
}
}
<?php
require_once "data/SayGoodBye.php";
use Data\Traits\{Person, SayHello, sayGoodBye};
$person = new Person();
$person->goodBye("Joko");
$person->hello("Budi");
$person->name = "Eko";
var_dump($person);
$person->run();