Home  >  Article  >  Backend Development  >  Use of interfaces for php development

Use of interfaces for php development

WBOY
WBOYOriginal
2016-08-08 09:26:31950browse

Inheritance simplifies the creation of objects and classes, and increases the reproducibility of code, but PHP only supports single inheritance. If you want to implement multiple inheritance, you must use multiple interfaces.
The interface is declared through the interface keyword, and the class can only contain unimplemented methods and some member variables. The format is as follows:
interface interfaceName{
function interfaceName1();
function interfaceName2();

}

Subclasses implement interfaces through the implements keyword. If multiple interfaces are to be implemented, commas "," should be used to connect each interface. And all unimplemented methods must be implemented in subclasses, otherwise PHP will error. The format is as follows:
class SubClass implments interfaceName1,interfaceName2{
function interfaceName1(){
//Function implementation
}
function interfaceName2(){
//Function implementation
}

}

The sample code is as follows:

<code><span><span><span><?php</span><span>//声明接口A</span><span><span>interface</span><span>A</span>{</span><span><span>function</span><span>Aa</span><span>()</span>;</span>
}
  <span>//声明接口B</span><span><span>interface</span><span>B</span>{</span><span><span>function</span><span>Bb</span><span>()</span>;</span>
}

 <span><span>class</span><span>Am</span><span>implements</span><span>A</span>{</span><span><span>function</span><span>Aa</span><span>()</span>{</span><span>echo</span><span>"Aa is a php coder"</span>;
    }
 }

 <span><span>class</span><span>Bm</span><span>implements</span><span>A</span>,<span>B</span>{</span><span><span>function</span><span>Aa</span><span>()</span>{</span><span>echo</span><span>"Mike is a php coder<br>"</span>;
    <span>echo</span><span>"Mike is an ios coder<br>"</span>;
    }

    <span><span>function</span><span>Bb</span><span>()</span>{</span><span>echo</span><span>"Jack is a java coder"</span>;
    }
 }

 <span>$jack</span> =<span>new</span> Am();
 <span>$bluce</span> =<span>new</span> Bm();

 <span>$jack</span>->Aa();
 <span>echo</span><span>"<br>"</span>;
 <span>$bluce</span>->Aa();
 <span>$bluce</span>->Bb();

<span>?></span></span></span></code>

The running results are as follows:

The above introduces the use of the interface for PHP development, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn