
//PHP新手入门教程2021(二):面向接口编程 回到今天的话题,PHP接口编程,PHP也是一门面向对象的语言,如果懂的设计模式的朋友,就知道接口在设计模式中应用是非常广泛的,简单的一句话:“不管黑猫白猫,能抓到耗子的就是好猫”,面向接口编程就是这个逻辑,不管实现细节,只在乎你能不能实现这个功能。 classDocumentStore{protected$data=[];publicfunctionaddDocument(Documentable$document){$key=$document->getId();$value=$document->getContent();$this->data[$key]=$value;}publicfunctiongetDocuments(){return$this->data;}} 就把这个简单认为是一个图书馆吧,其中有两个功能,一个是保存文档 interfaceDocumentable{publicfunctiongetId();publicfunctiongetContent();} 我们只要实现上面的接口,就不需要关心文档实际的存储媒介,像如下代码: HTMLdocument$htmlDoc=newHtmlDocument('https://php.net');$documentStore->addDocument($htmlDoc);//Addvideodocument$videoDoc=newVideoDocument(fopen('seozen.mp4','rb'));$documentStore->addDocument($videoDoc);//Addaudiodocument$audioDoc=newAudioDocument(fopen('seozen.mp3','rb'));$documentStore->addDocument($audioDoc);print_r($documentStore->getDocuments()); 如果以后有新的存储媒介,也只要再实现下这个接口就可以,不需要去改去太多的代码,更多的接口应用会在其它的文章来介绍,这里就先简单的举个例子,让大家有个概念。 您的电子邮箱地址不会被公开。必填项已用*标注 Copyright©2021-2023SEO禅专注SEO优化-分享SEO技术 本文地址:https://www.badfl.com/article/2f4192b2178080c36a73.htmladdDocument一个是获取文档getDocuments,对于现代的图书馆来说,资源已经除了纸质,其它各种媒介都有可能,所以我们这里有一个Documentable的接口,只要使用了这个接口,就可以存到这个虚拟的图书馆里,看下这个接口: