PHP OOP에서 트레이트 작업 시 메서드 우선순위

클래스와 트레이트에 동일한 이름의 메서드가 있는 경우, 클래스 메서드가 트레이트 메서드를 재정의합니다:

php<?php
  trait TestTrait
  {
    // method라는 이름의 메서드:
    public function method()
    {
      return 'trait';
    }
  }
  
  class TestClass
  {
    use TestTrait;
    
    // method라는 동일한 이름의 메서드:
    public function method()
    {
      return 'test';
    }
  }
  
  $test = new TestClass;
  echo $test->method(); // 'test'를 출력함 - 클래스 자체의 메서드가 실행됨
?>

클래스 자체에 해당 메서드가 없지만, 트레이트 메서드와 부모 클래스 메서드 간의 이름 충돌이 있는 경우, 트레이트 메서드가 우선순위를 가집니다:

php<?php
  trait TestTrait
  {
    // method라는 이름의 메서드:
    public function method()
    {
      return 'trait';
    }
  }
  
  // 부모 클래스:
  class ParentClass
  {
    // method라는 이름의 메서드:
    public function method()
    {
      return 'parent';
    }
  }
  
  // 클래스는 부모로부터 method 메서드를 상속받음:
  class TestClass extends ParentClass
  {
    use TestTrait;
  }
  
  $test = new TestClass;
  echo $test->method(); // 트레이트가 우선순위를 가지므로 'trait'를 출력함
?>