PHP:我可以在接口中使用字段吗?

时间:2010-02-12 11:52:13

标签: php interface

在PHP中,我可以指定一个接口来创建字段,还是将PHP接口限制为函数?

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

如果没有,我意识到我可以在接口中公开一个getter函数:

public GetField();

5 个答案:

答案 0 :(得分:47)

您无法指定成员。你必须通过吸气剂和制定者表明他们的存在,就像你一样。但是,您可以指定常量:

interface IFoo
{
    const foo = 'bar';    
    public function DoSomething();
}

请参阅http://www.php.net/manual/en/language.oop5.interfaces.php

答案 1 :(得分:19)

迟到的答案,但要获得此处所需的功能,您可能需要考虑包含字段的抽象类。抽象类看起来像这样:

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;
    }
}

对那些仍然充满好奇和兴趣的人来说,还有另一种解决方案。 :)

答案 2 :(得分:14)

接口仅用于支持方法。

这是因为存在接口以提供可由其他对象访问的公共API。

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

答案 3 :(得分:13)

使用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');
    }
}

答案 4 :(得分:5)

您无法在interface中指定属性:只允许方法(并且有意义,因为接口的目标是指定API)


在PHP中,尝试在接口中定义属性应该引发致命错误:这部分代码:

interface A {
  public $test;
}

会给你:

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