2010-02-12 148 views
39

在PHP中,我可以指定具有字段的接口,还是PHP接口仅限于函数?PHP:我可以在接口中使用字段吗?

<?php 
interface IFoo 
{ 
    public $field; 
    public function DoSomething(); 
    public function DoSomethingElse(); 
} 
?> 

如果没有,我知道我可以公开一个吸气剂与界面中的功能:

public GetField(); 
+0

警告:如果你得到一个下来投给问这个不感到惊讶 - 检查PHP手册的OOP部分。 – Andreas 2010-02-12 11:55:42

+3

是的,手册的快速扫描显示他们只使用界面中的功能。可能刚刚跳过那部分。无论如何,我只是想确定一下。 – Scott 2010-02-12 12:16:59

回答

11

接口被设计为仅支持的方法。

这是因为接口存在提供一个公共API,然后可以由其他对象访问。

公开访问的属性实际上会违反实现该接口的类中的数据封装。

5

不能指定在interface属性:只有方法允许(和意义,因为接口的目标是要指定一个API)


在PHP中,试图定义一个属性接口应引起致命错误:这个代码部分:

interface A { 
    public $test; 
} 

会给你:

Fatal error: Interfaces may not include member variables in... 
14

晚的答案,但得到的功能想在这里,你可能要考虑包含您的域的抽象类。抽象类是这样的:

abstract class Foo 
{ 
    public $member; 
} 

虽然你仍然可以有接口:

interface IFoo 
{ 
    public function someFunction(); 
} 

然后你有你的子类是这样的:

class bar extends Foo implements IFoo 
{ 
    public function __construct($memberValue = "") 
    { 
     // Set the value of the member from the abstract class 
     $this->member = $memberValue; 
    } 

    public function someFunction() 
    { 
     // Echo the member from the abstract class 
     echo $this->member; 
    } 
} 

有一个替代的解决方案对那些仍然好奇和感兴趣的人来说。 :)

+3

我很好奇,很感兴趣。如何保证会员的存在? :) – deb0rian 2013-09-01 08:14:11

+0

类'Foo'应该实现接口'IFoo',它是抽象的,它会清楚地显示'Foo'的目的:简化接口的实现。 – 2014-04-18 13:52:31

+0

同意,@PeterM。抽象类可能会实现接口而不是最终的类。取决于你是否总是希望被强制执行'someFunction()'。 – 2014-05-19 11:18:59

11

使用getter setter。但是,在许多类中实现许多getter和setter可能很乏味,而且它会使类代码混乱。和you repeat yourself

由于PHP 5.4,你可以用traits提供字段和方法的类,即:

interface IFoo 
{ 
    public function DoSomething(); 
    public function DoSomethingElse(); 
    public function setField($value); 
    public function getField(); 
} 

trait WithField 
{ 
    private $_field; 
    public function setField($value) 
    { 
     $this->_field = $value; 
    } 
    public function getField() 
    { 
     return $this->field; 
    } 
} 

class Bar implements IFoo 
{ 
    use WithField; 

    public function DoSomething() 
    { 
     echo $this->getField(); 
    } 
    public function DoSomethingElse() 
    { 
     echo $this->setField('blah'); 
    } 
} 

这是特别有用的,如果你有一些基类继承,需要实现一些接口。

class CooCoo extends Bird implements IFoo 
{ 
    use WithField; 

    public function DoSomething() 
    { 
     echo $this->getField(); 
    } 
    public function DoSomethingElse() 
    { 
     echo $this->setField('blah'); 
    } 
} 
+0

好的,但在我看来,抽象类更具可读性。 – 2014-11-21 09:11:06

+1

但是对于抽象类,只能从这个类继承。有了特质和接口,你就有了多重继承。我加上它来回答。 – 2014-11-21 11:05:11

相关问题