运用接口(interface),能够指定某个类必需完成哪些要领,但不须要定义这些要领的具体内容。
接口是经由过程 interface 关键字来定义的,就像定义一个规范的类一样,但个中定义一切的要领都是空的。
接口中定义的一切要领都必需是公有,这是接口的特征。(引荐进修:PHP编程从入门到通晓)
完成(implements)
要完成一个接口,运用 implements 操作符。类中必需完成接口中定义的一切要领,不然会报一个致命毛病。类能够完成多个接口,用逗号来分开多个接口的称号。
Note:
完成多个接口时,接口中的要领不能有重名。
Note:
接口也能够继续,经由过程运用 extends 操作符。
Note:
类要完成接口,必需运用和接口中所定义的要领完全一致的体式格局。不然会致使致命毛病。
接口实例
<?php // 声明一个'iTemplate'接口 interface iTemplate { public function setVariable($name, $var); public function getHtml($template); } // 完成接口 // 下面的写法是准确的 class Template implements iTemplate { private $vars = array(); public function setVariable($name, $var) { $this->vars[$name] = $var; } public function getHtml($template) { foreach($this->vars as $name => $value) { $template = str_replace('{' . $name . '}', $value, $template); } return $template; } } // 下面的写法是毛病的,会报错,由于没有完成 getHtml(): // Fatal error: Class BadTemplate contains 1 abstract methods // and must therefore be declared abstract (iTemplate::getHtml) class BadTemplate implements iTemplate { private $vars = array(); public function setVariable($name, $var) { $this->vars[$name] = $var; } } ?>
以上就是php什么是接口的细致内容,更多请关注ki4网别的相干文章!