>  기사  >  백엔드 개발  >  PHP 인터페이스

PHP 인터페이스

WBOY
WBOY원래의
2024-08-29 13:00:281057검색

PHP 인터페이스는 복잡성을 포함하지 않고 실행해야 하는 클래스의 공개 메소드와 특정 메소드가 구현되는 방법을 나타내는 유용한 프로그램을 만드는 데 도움이 됩니다. PHP 인터페이스는 메소드의 내용이 아닌 인수와 이름만 정의하며, 인터페이스를 구현하는 모든 클래스는 인터페이스에 정의된 모든 메소드를 구현해야 합니다.

광고 이 카테고리에서 인기 있는 강좌 PHP 개발자 - 전문 분야 | 8개 코스 시리즈 | 3가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

이러한 인터페이스는 클래스와 유사하지만 클래스 구문만 선언의 인터페이스 키워드로 대체됩니다.

구문:

<?php
Interface interface_name
{
//List of methods
}
?>

PHP 인터페이스는 왜 필요한가요?

동일한 클래스에서 하나의 인터페이스를 구현할 수 있지만 동일한 클래스 내에서 더 많은 인터페이스를 만들 수 있습니다. 클래스는 구현 방법에 대한 제한 없이 PHP 객체 인터페이스를 사용하여 특정 메소드를 구현할 수 있습니다. 인터페이스는 클래스와 동일하거나 유사하지만 PHP의 인터페이스 키워드는 메소드를 사용하지 않고 내용이 정의된 클래스 키워드를 대체합니다. 인터페이스 내에서 생성자를 선언할 수 있습니다. 클래스 또는 클래스는 각 인터페이스를 쉼표로 구분하여 필요할 때 여러 인터페이스를 구현할 수 있습니다.

"확장" 작업을 사용하여 PHP 프로그래밍 언어에서 클래스를 확장할 수 있습니다. PHP 인터페이스는 추상화의 다음 단계입니다. 추상 클래스와 유사하지만 약간의 차이가 있습니다. 인터페이스 또는 인터페이스를 사용하면 클래스의 메서드를 정의하는 데 도움이 되는 코드를 만들 수 있지만 해당 메서드에 코드를 추가할 수도 없는 반면 추상 클래스는 PHP 인터페이스 또는 인터페이스와 동일하거나 유사한 것을 허용합니다. 하지만 추상 클래스에서는 메서드에 코드를 추가할 수 있습니다.

PHP 인터페이스 작업

PHP 5.3.9 이전 버전에서는 모호함을 야기하기 때문에 동일한 이름을 가진 인터페이스 두 개만 구현할 수도 없었습니다. 무엇보다도 최신 PHP 버전에서는 동일/유사한 서명을 가진 중복 메서드를 허용합니다. 인터페이스를 구현하는 클래스는 "Liskov 대체 원칙 - LSP"와 호환되는 메서드 시그니처를 사용해야 합니다. 메소드 시그니처를 사용하지 않으면 결과에 치명적인 오류가 발생합니다.

클래스는 인터페이스를 사용하여 기존 콘텐츠 없이 메서드로만 구성된 메서드에 콘텐츠를 추가합니다. 인터페이스의 메소드는 대부분 제한 없이 공개됩니다. PHP 인터페이스는 클래스와 동일/유사하지 않습니다. 클래스는 여러 인터페이스를 상속할 수 있지만 클래스는 한 번에 하나의 클래스만 상속할 수 있습니다. 이런 장점도 있습니다. 변수는 인터페이스/인터페이스 내부에 존재합니다.

PHP 인터페이스의 예

다음은 PHP 인터페이스의 예입니다.

예시 #1

아래 예에서는 두 가지 메서드만 언급된 "MyInterfaceName1"이라는 인터페이스를 선언했습니다. 콘텐츠를 사용하지 않고 인터페이스 내부의 method11 및 method21입니다. 그런 다음 "MyClassName1"이라는 클래스는 "MyInterfaceName1" 인터페이스를 구현하고 요구 사항에 따라 사용 가능한 메서드를 사용합니다.

정의에서 알 수 있듯이 인터페이스도 내용이 없는 메소드로 구성됩니다. 인터페이스 구현 중에는 수업 시간에만 내용을 논의하겠습니다. 때때로 사람들은 이러한 인터페이스 메소드를 추상 메소드라고 부릅니다.

코드:

<?php
interface MyInterfaceName1{
public function method11();
public function method21();
}
class MyClassName1 implements MyInterfaceName1{
public function method11(){
echo "Now Method11 Called" . "<br>";
}
public function method21(){
echo "Now Method21 Called". "\n";
}
}
$obj = new MyClassName1;
$obj->method11();
$obj->method21();
?>

출력:

PHP 인터페이스

예시 #2

아래 프로그램에는 각각 고유한 메소드를 가진 두 개의 인터페이스가 포함되어 있습니다. 그런 다음 info()라는 메서드를 사용하여 클래스 Bird를 만듭니다. 이제 Dove 클래스는 CanFly PHP 인터페이스를 구현하여 인쇄 문을 가져오는 Class Bird로 확장됩니다. 인쇄 문/기타는 메서드만 있기 때문에 인터페이스 내부에 존재하지 않기 때문입니다.

Bird 2의 특성에 따라 각각 1개의 메소드를 가진 “CanFly”와 “CanSwim” 인터페이스가 만들어졌습니다. 그것은 fly()와 swim()입니다. "Bird" 클래스의 "info()" 메소드는 새의 유형과 그것이 실제로 새인지를 결정하기 위한 명령문을 인쇄/반향합니다. “bird” 클래스를 확장하고 “CanFly” 및 “CanSwim” 인터페이스를 구현하여 Dove, Penguin, Duck과 같은 새의 세부 정보를 “$name1” 변수에 하나씩 배치합니다. 또한 인터페이스에 대한 에코 문을 추가하세요.

We have created a function named “describe($bird)” that utilizes the “CanFly” and “CanSwim” interfaces to determine if a creature is a bird. If the $ bird doesn’t satisfy the fly() and swim(), the else condition exists in the PHP program’s output. Now calling all the described functions with the 3 bird classes. You will get the output of the 3 birds as needed. Check out below. It is a simple description, but you will know how it is happening if you look at the code and output of the PHP Program below.

Code:

<?php
/**
* This is An example of the duck typing in the PHP Script
*/
interface CanFly1 {
public function fly1();
}
interface CanSwim1 {
public function swim1();
}
class Bird1 {
public function info1() {
echo "I am a {$this->name1}\n";
echo "I am a bird\n";
}
}
/**
* This is some of the implementations of the birds
*/
class Dove1 extends Bird1 implements CanFly1 {
var $name1 = "Dove";
public function fly1() {
echo "I fly\n";
}
}
class Penguin1 extends Bird1 implements CanSwim1 {
var $name1 = "Penguin";
public function swim1() {
echo "I swim\n";
}
}
class Duck1 extends Bird1 implements CanFly1, CanSwim1 {
var $name1 = "Duck";
public function fly1() {
echo "I fly\n";
}
public function swim1() {
echo "I swim\n";
}
}
/**
* This is one of the simple function which is to describe a bird
*/
function describe1($bird1) {
if ($bird1 instanceof Bird1) {
$bird1->info1();
if ($bird1 instanceof CanFly1) {
$bird1->fly1();
}
if ($bird1 instanceof CanSwim1) {
$bird1->swim1();
}
} else {
die("This is not a bird. I cannot describe it.");
}
}
// Now describing the birds
describe1(new Penguin1);
echo "---\n<br>";
describe1(new Dove1);
echo "---\n<br>";
describe1(new Duck1);

Output:

PHP 인터페이스

Advantages

Following are some of the advantages given.

  • It will allow the unrelated classes to implement similar methods without considering their positions in the class with an inheritance hierarchy.
  • We can model many inheritances in this approach by implementing multiple interfaces in a class, but the class can only extend one class.
  • It can implement an inheritance which can save the caller from the implementation of the object methods fully. This implementation of the heritance concept is also helpful to focus on the object’s interface so that the caller interface doesn’t even affect it.

Recommended Article

This is a guide to the PHP Interface. Here we discuss the PHP Interface, its Advantages, and its various examples to understand the PHP Interface concept briefly. You can also go through our other suggested articles to learn more –

  1. PHP Encryption
  2. PHP Frameworks
  3. Abstract Class in PHP
  4. PHP Superglobal Variables

위 내용은 PHP 인터페이스의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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