一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

浅析php接口操作interface关键字的用法及应用实例

时间:2015-01-20 编辑:简简单单 来源:一聚教程网

接口是一种约束形式,其中只包括成员定义,不包含成员实现的内容。用接口(interface),你可以指定某个类必须实现哪些方法,但不需要定义这些方法的具体内容。 我们可以通过interface来定义一个接口,就像定义一个标准的类一样,但其中定义所有的方法都是空的。

接口中定义的所有方法都必须是public,这是接口的特性。

实现

  要实现一个接口,可以使用implements操作符。类中必须实现接口中定义的所有方法,否则会报一个fatal错误。如果要实现多个接口,可以用逗号来分隔多个接口的名称。

    Note:  

    实现多个接口时,接口中的方法不能有重名。  

    Note:  

    接口也可以继承,通过使用extends操作符。  

常量

接口中也可以定义常量。接口常量和类常量的使用完全相同。它们都是定值,不能被子类或子接口修改。


范例

Example #1 接口代码示例


// 声明一个'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;
   }
}

// 下面的写法是错误的,会报错:
// 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;
   }
}
?>

Example #2 Extendable Interfaces

interface a
{
   public function foo();
}

interface b extends a
{
   public function baz(Baz $baz);
}

// 正确写法
class c implements b
{
   public function foo()
   {
   }

   public function baz(Baz $baz)
   {
   }
}

// 错误写法会导致一个fatal error
class d implements b
{
   public function foo()
   {
   }

   public function baz(Foo $foo)
   {
   }
}
?>

Example #3 多个接口间的继承

interface a
{
   public function foo();
}

interface b
{
   public function bar();
}

interface c extends a, b
{
   public function baz();
}

class d implements c
{
   public function foo()
   {
   }

   public function bar()
   {
   }

   public function baz()
   {
   }
}
?>

Example #4 使用接口常量

interface a
{
   const b = 'Interface constant';
}

// 输出接口常量
echo a::b;

// 错误写法,因为常量的值不能被修改。接口常量的概念和类常量是一样的。
class b implements a
{
   const b = 'Class constant';
}
?>

热门栏目