PHP'de OOP'de Traitlerle Çalışırken Metotların Önceliği
Bir sınıfta ve bir traitte aynı isimde bir metot varsa, sınıfın metodu traitin metodunu geçersiz kılacaktır:
<?php
trait TestTrait
{
// method adında metot:
public function method()
{
return 'trait';
}
}
class TestClass
{
use TestTrait;
// Aynı isimde method adında metot:
public function method()
{
return 'test';
}
}
$test = new TestClass;
echo $test->method(); // 'test' çıktısını verir - sınıfın kendi metodu çalıştı
?>
Eğer sınıfın kendisi böyle bir metoda sahip değilse, ancak trait metotları ile ebeveyn sınıfın metotları arasında isim çakışması varsa, trait metotları önceliğe sahiptir:
<?php
trait TestTrait
{
// method adında metot:
public function method()
{
return 'trait';
}
}
// Ebeveyn sınıf:
class ParentClass
{
// method adında metot:
public function method()
{
return 'parent';
}
}
// Sınıf, method metodunu ebeveynden miras alır:
class TestClass extends ParentClass
{
use TestTrait;
}
$test = new TestClass;
echo $test->method(); // 'trait' çıktısını verir, çünkü trait önceliğe sahiptir
?>