소개
PHP는 다중 상속을 지원하지 않습니다. 이 제한은 특성의 기능으로 어느 정도 극복됩니다. . 코드 재사용의 메커니즘입니다. 특성의 정의는 클래스와 유사합니다. 그러나 직접 인스턴스화할 수는 없습니다. 대신 사용을 통해 특성의 기능을 클래스에서 사용할 수 있습니다. 예어. 따라서 클래스는 트레이트에 정의된 메서드를 사용하거나 재정의할 수도 있습니다. 이것은 상속될 수 있는 다른 모든 상위 클래스에 추가됩니다.
특성은 또한 인터페이스와 유사합니다. 차이점은 인터페이스가 클래스를 구현하여 수행해야 하는 내부 메소드 정의를 제공하지 않는다는 것입니다. 그러나 Trait 메서드는 정의를 제공하며 이 정의는 해당 특성을 사용하는 클래스에 의해 재정의되거나 재정의되지 않을 수 있습니다.
구문
<?php
trait testtrait{
public function test1(){
//body of method
}
}
//using trait
class testclass{
use testtrait
//rest of members in class
}
?> 예시
다음 코드에서는 두 가지 메서드가 있는 특성이 메서드 중 하나를 재정의하는 클래스에서 사용됩니다.
예시
<?php
//definition of trait
trait testtrait{
public function test1(){
echo "test1 method in trait\n";
}
public function test2(){
echo "test2 method in trait\n";
}
}
//using trait
class testclass{
use testtrait;
public function test1(){
echo "test1 method overridden\n";
}
}
$obj=new testclass();
$obj->test1();
$obj->test2();
?> 출력
출력은 아래와 같습니다 -
test1 method overridden test2 method in trait
하위 클래스의 특성
이것이 특성의 주요 장점입니다. 부모가 있는 클래스도 특성을 사용할 수 있으며 해당 메서드를 재정의하도록 선택할 수 있습니다. 따라서 다중 상속을 효과적으로 달성합니다. 이 기능의 예는 다음과 같습니다 -
예시
<?php
//definition of trait
trait testtrait{
public function test1(){
echo "test1 method in trait\n";
}
}
//parent class
class parentclass{
public function test2(){
echo "test2 method in parent\n";
}
}
//using trait and parent class
class childclass extends parentclass{
use testtrait;
public function test1(){
echo "parent method overridden\n";
}
public function test2(){
echo "trait method overridden\n";
}
}
$obj=new childclass();
$obj->test1();
$obj->test2();
?> 출력
위의 코드는 다음 결과를 생성합니다 -
parent method overridden trait method overridden
인터페이스가 있는 특성
인터페이스를 구현하고 다른 부모 클래스를 확장하고 동시에 특성을 사용하는 클래스를 가질 수 있습니다.
예시
<?php
//definition of trait
trait mytrait{
public function test1(){
echo "test1 method in trait1\n";
}
}
class myclass{
public function test2(){
echo "test2 method in parent class\n";
}
}
interface myinterface{
public function test3();
}
//using trait and parent class
class testclass extends myclass implements myinterface{
use mytrait;
public function test3(){
echo "implementation of test3 method\n";
}
}
$obj=new testclass();
$obj->test1();
$obj->test2();
$obj->test3();
?> 출력
이것은 다음과 같은 출력을 생성합니다 -
test1 method in trait1 test2 method in parent class implementation of test3 method
충돌 해결
클래스가 공통 메서드로 두 개의 특성을 사용하는 경우 범위 확인 연산자와 대신에 의해 충돌이 해결됩니다. 키워드
예시
<?php
trait trait1{
public function test1(){
echo "test1 method in trait1\n";
}
public function test2(){
echo "test2 method in trait1\n";
}
}
trait trait2{
public function test1(){
echo "test1 method in trait2\n";
}
public function test2(){
echo "test2 method in trait2\n";
}
}
//using trait and parent class
class testclass {
use trait1, trait2{
trait1::test1 insteadof trait2;
trait2::test2 insteadof trait1;
}
}
$obj=new testclass();
$obj->test1();
$obj->test2();
?> 출력
위의 스크립트는 다음 결과를 생성합니다.
test1 method in trait1 test2 method in trait2