Metožu prioritāte, strādājot ar PHP OOP trait
Ja klasē un trait ir tādas pašas metodes, tad klases metode pārrakstīs trait metodi:
<?php
trait TestTrait
{
// Metode ar nosaukumu method:
public function method()
{
return 'trait';
}
}
class TestClass
{
use TestTrait;
// Tāda pati metode ar nosaukumu method:
public function method()
{
return 'test';
}
}
$test = new TestClass;
echo $test->method(); // izvadīs 'test' - nostrādāja pašas klases metode
?>
Ja pašai klasei nav šādas metodes, bet pastāv trait metožu un vecāku klases metožu nosaukumu konflikts, tad trait metodes ir prioritāte:
<?php
trait TestTrait
{
// Metode ar nosaukumu method:
public function method()
{
return 'trait';
}
}
// Vecāku klase:
class ParentClass
{
// Metode ar nosaukumu method:
public function method()
{
return 'parent';
}
}
// Klase manto metodi method no vecāka:
class TestClass extends ParentClass
{
use TestTrait;
}
$test = new TestClass;
echo $test->method(); // izvadīs 'trait', jo trait ir prioritāte
?>