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

Sco*_*ott 43 php interface

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

<?php
interface IFoo
{
    public $field;
    public function DoSomething();
    public function DoSomethingElse();
}
?>
Run Code Online (Sandbox Code Playgroud)

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

public GetField();
Run Code Online (Sandbox Code Playgroud)

Gor*_*don 48

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

interface IFoo
{
    const foo = 'bar';    
    public function DoSomething();
}
Run Code Online (Sandbox Code Playgroud)

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


小智 21

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

abstract class Foo
{
    public $member;
}
Run Code Online (Sandbox Code Playgroud)

虽然你仍然可以拥有界面:

interface IFoo
{
    public function someFunction();
}
Run Code Online (Sandbox Code Playgroud)

然后你有这样的孩子班:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 我好奇并感兴趣.如何保证会员的存在?:) (4认同)

Noa*_*ich 14

接口仅用于支持方法.

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

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


小智 13

使用getter setter.但是在许多类中实现许多getter和setter可能会很繁琐,而且它会使类代码混乱.而你重复自己!

从PHP 5.4开始,您可以使用特征为类提供字段和方法,即:

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您必须从某个基类继承并需要实现某个接口,这是特别有用的.

class CooCoo extends Bird implements IFoo
{
    use WithField;

    public function DoSomething()
    {
        echo $this->getField();
    }
    public function DoSomethingElse()
    {
        echo $this->setField('blah');
    }
}
Run Code Online (Sandbox Code Playgroud)


Pas*_*TIN 5

您不能在以下内容中指定属性interface:仅允许方法(并且有意义,因为接口的目标是指定API)


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

interface A {
  public $test;
}
Run Code Online (Sandbox Code Playgroud)

会给你 :

Fatal error: Interfaces may not include member variables in...
Run Code Online (Sandbox Code Playgroud)