Prednost metod pri delu s trait-i v OOP v PHP
Če razred in trait vsebujeta metodo z istim imenom, bo metoda razreda preglasila metodo traita:
<?php
trait TestTrait
{
// Metoda z imenom method:
public function method()
{
return 'trait';
}
}
class TestClass
{
use TestTrait;
// Enaka metoda z imenom method:
public function method()
{
return 'test';
}
}
$test = new TestClass;
echo $test->method(); // izpiše 'test' - delovala je metoda razreda
?>
Če razred sam nima takšne metode, vendar obstaja konflikt imen med metodami traita in metodami nadrejenega razreda, imajo metode traita prednost:
<?php
trait TestTrait
{
// Metoda z imenom method:
public function method()
{
return 'trait';
}
}
// Nadrejeni razred:
class ParentClass
{
// Metoda z imenom method:
public function method()
{
return 'parent';
}
}
// Razred podeduje metodo method od nadrejenega razreda:
class TestClass extends ParentClass
{
use TestTrait;
}
$test = new TestClass;
echo $test->method(); // izpiše 'trait', ker ima trait prednost
?>