>  기사  >  백엔드 개발  >  PHP에서 특성을 사용하는 방법 요약

PHP에서 특성을 사용하는 방법 요약

伊谢尔伦
伊谢尔伦원래의
2017-07-03 11:20:161020검색

PHP는 단일 상속 언어입니다. PHP 5.4 Traits이 등장하기 전에는 PHP 클래스가 두 기본 클래스의 속성이나 메서드를 동시에 상속받을 수 없었습니다. PHP의 Traits 조합 기능은 Go 언어의 기능과 유사합니다. 클래스에서 use 키워드를 사용하여 조합할 Trait의 이름을 선언합니다. 그러나 특정 Trait의 선언은 trait 키워드를 사용합니다. 직접 인스턴스화할 수 없습니다. 구체적인 사용법은 아래 코드를 참조하세요.

<?php
  trait Drive {
    public $carName = &#39;trait&#39;;
    public function driving() {
      echo "driving {$this->carName}\n";
    }
  }
  class Person {
    public function eat() {
      echo "eat\n";
    }
  }
  class Student extends Person {
    use Drive;
    public function study() {
      echo "study\n";
    }
  }
  $student = new Student();
  $student->study();
  $student->eat();
  $student->driving();

출력 결과는 다음과 같습니다.

study
eat
driving trait

위의 예에서 Student 클래스는 Person을 상속받아 eat 메소드를 가지며, Drive를 결합하여 운전 메소드와 속성 carName.

Trait, 기본 클래스, 이 클래스에 같은 이름을 가진 속성이나 메서드가 있으면 결국 어떤 것이 유지되나요? 다음 코드로 테스트해 보세요.

<?php 
  trait Drive {
    public function hello() {
      echo "hello drive\n";
    }
    public function driving() {
      echo "driving from drive\n";
    }
  }
  class Person {
    public function hello() {
      echo "hello person\n";
    }
    public function driving() {
      echo "driving from person\n";
    }
  }
  class Student extends Person {
    use Drive;
    public function hello() {
      echo "hello student\n";
    }
  }
  $student = new Student();
  $student->hello();
  $student->driving();

출력 결과는 다음과 같습니다.

hello student
driving from drive

그래서 메소드나 속성의 이름이 같으면 현재 클래스의 메소드가 특성의 메소드를 재정의하고, 특성 메소드는 기본 클래스 메소드의 메소드를 대체합니다.

여러 특성을 결합하려면 특성 이름을 쉼표로 구분하세요.

use Trait1, Trait2

여러 특성에 동일한 이름의 메서드나 속성이 포함되어 있으면 어떻게 되나요? 대답은 여러 개의 결합된 특성에 동일한 이름의 속성이나 메서드가 포함된 경우 충돌을 해결하기 위해 명시적으로 선언해야 하며 그렇지 않으면 치명적인 오류가 발생한다는 것입니다.

<?php
trait Trait1 {
  public function hello() {
    echo "Trait1::hello\n";
  }
  public function hi() {
    echo "Trait1::hi\n";
  }
}
trait Trait2 {
  public function hello() {
    echo "Trait2::hello\n";
  }
  public function hi() {
    echo "Trait2::hi\n";
  }
}
class Class1 {
  use Trait1, Trait2;
}

출력 결과는 다음과 같습니다.

PHP Fatal error: Trait method hello has not been applied, because there are collisions with other trait methods on Class1 in ~/php54/trait_3.php on line 20

충돌을 해결하려면 of 및 as연산자를 사용하세요. 대신of는 다른 메서드를 대체하는 반면 as는 해당 메서드에 별칭을 제공합니다.

<?php
trait Trait1 {
  public function hello() {
    echo "Trait1::hello\n";
  }
  public function hi() {
    echo "Trait1::hi\n";
  }
}
trait Trait2 {
  public function hello() {
    echo "Trait2::hello\n";
  }
  public function hi() {
    echo "Trait2::hi\n";
  }
}
class Class1 {
  use Trait1, Trait2 {
    Trait2::hello insteadof Trait1;
    Trait1::hi insteadof Trait2;
  }
}
class Class2 {
  use Trait1, Trait2 {
    Trait2::hello insteadof Trait1;
    Trait1::hi insteadof Trait2;
    Trait2::hi as hei;
    Trait1::hello as hehe;
  }
}
$Obj1 = new Class1();
$Obj1->hello();
$Obj1->hi();
echo "\n";
$Obj2 = new Class2();
$Obj2->hello();
$Obj2->hi();
$Obj2->hei();
$Obj2->hehe();

출력 결과는 다음과 같습니다.

Trait2::hello
Trait1::hi

Trait2::hello
Trait1::hi
Trait2::hi
Trait1::hello

as 키워드에는 메소드의 액세스 제어를 수정하는 또 다른 용도가 있습니다.

<?php
  trait Hello {
    public function hello() {
      echo "hello,trait\n";
    }
  }
  class Class1 {
    use Hello {
      hello as protected;
    }
  }
  class Class2 {
    use Hello {
      Hello::hello as private hi;
    }
  }
  $Obj1 = new Class1();
  $Obj1->hello(); # 报致命错误,因为hello方法被修改成受保护的
  $Obj2 = new Class2();
  $Obj2->hello(); # 原来的hello方法仍然是公共的
  $Obj2->hi(); # 报致命错误,因为别名hi方法被修改成私有的

Trait는 Trait와 결합하여 추상 메소드, static 속성 및 속성을 지원할 수도 있습니다. 정적 메소드, 테스트 코드는 다음과 같습니다.

<?php
trait Hello {
  public function sayHello() {
    echo "Hello\n";
  }
}
trait World {
  use Hello;
  public function sayWorld() {
    echo "World\n";
  }
  abstract public function getWorld();
  public function inc() {
    static $c = 0;
    $c = $c + 1;
    echo "$c\n";
  }
  public static function doSomething() {
    echo "Doing something\n";
  }
}
class HelloWorld {
  use World;
  public function getWorld() {
    return &#39;get World&#39;;
  }
}
$Obj = new HelloWorld();
$Obj->sayHello();
$Obj->sayWorld();
echo $Obj->getWorld() . "\n";
HelloWorld::doSomething();
$Obj->inc();
$Obj->inc();

출력 결과는 다음과 같습니다.

Hello
World
get World
Doing something
1
2

위 내용은 PHP에서 특성을 사용하는 방법 요약의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.