Trait adalah cara untuk memasukkan method ke dalam suatu Class tanpa memakai inheritance (extends). Sebuah class bisa memakai lebih dari satu trait.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php class Mobil{ //Memasukkan Trait use TurboCharger; private $merk; private $hp = 300; public function __construct($merk){ $this->merk = $merk; } public function getMerk(){ return $this->merk; } public function getHp(){ return $this->hp; } } trait TurboCharger{ public function turbo($hp){ $this->hp += $hp; } } $nissan = new Mobil('Nissan Skyline GT-R'); echo $nissan->getMerk() . "<br>"; echo 'HP Asli : '.$nissan->getHp() . " PK <br>"; $nissan->turbo(50); echo 'HP Turbocharged : ' . $nissan->getHp() . " PK <br>"; |
Untuk menggunakan trait, gunakan keyword use diikuti nama Trait nya.
Menggunakan lebih dari satu trait:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<?php class Mobil{ //Memasukkan Trait use TurboCharger; use Nitro; private $merk; private $hp = 300; public function __construct($merk){ $this->merk = $merk; } public function getMerk(){ return $this->merk; } public function getHp(){ return $this->hp; } } trait TurboCharger{ public function turbo($hp){ $this->hp += $hp; } } trait Nitro{ private $maksHp = 150; public function nos(){ $this->hp += $this->maksHp; } } $nissan = new Mobil('Nissan Skyline GT-R'); echo $nissan->getMerk() . "<br>"; echo 'HP Asli : '.$nissan->getHp() . " PK <br>"; $nissan->turbo(50); echo 'HP Turbocharged : ' . $nissan->getHp() . " PK <br>"; $nissan->nos(); echo 'HP Nitro : '.$nissan->getHp() . " PK <br>"; |
Penggunaan trait perlu hati-hati karena rawan duplikasi kode dan terlihat tidak rapi karena banyak kode yang disebar ke dalam trait.
Penggunaan trait yang tepat hanya untuk kasus tertentu saja, gunakan trait untuk class yang membutuhkan saja.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<?php abstract class Mobil{ protected $merk; protected $hp; public function __construct($merk){ $this->merk = $merk; } public function getMerk(){ return $this->merk; } public function setHp($hp){ $this->hp = $hp; } public function getHp(){ return $this->hp; } } trait TurboCharger{ private $hpTurbo = 150; public function turbo(){ $this->hp += $this->hpTurbo; } } class Honda extends Mobil{} class Toyota extends Mobil{} class Pontiac extends Mobil{ use TurboCharger; } $honda = new Honda('Honda Civic'); $honda->setHp(150); echo $honda->getMerk() . " - " . $honda->getHp() . " PK <br>"; $toyota = new Toyota('Toyota Camry'); $toyota->setHp(250); echo $toyota->getMerk() . " - " . $toyota->getHp() . " PK <br>"; $pontiac = new Pontiac('Pontiac GTO'); $pontiac->setHp(200); $pontiac->turbo(); echo $pontiac->getMerk() . " - " . $pontiac->getHp() . " PK <br>"; |