Priority of Methods When Working with Traits in OOP in PHP
If a class and a trait have a method with the same name, the class method will override the trait method:
<?php
trait TestTrait
{
// Method named method:
public function method()
{
return 'trait';
}
}
class TestClass
{
use TestTrait;
// The same method named method:
public function method()
{
return 'test';
}
}
$test = new TestClass;
echo $test->method(); // will output 'test' - the class's own method worked
?>
If the class itself does not have such a method, but there is a name conflict between the trait's methods and the methods of the parent class, then the trait's methods have priority:
<?php
trait TestTrait
{
// Method named method:
public function method()
{
return 'trait';
}
}
// Parent class:
class ParentClass
{
// Method named method:
public function method()
{
return 'parent';
}
}
// The class inherits the method method from the parent:
class TestClass extends ParentClass
{
use TestTrait;
}
$test = new TestClass;
echo $test->method(); // will output 'trait', because the trait has priority
?>