2010-02-12 22 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

相關問題