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

2022-08-30 10:03:22

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

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

如果没有,我意识到我可以在界面中将getter公开为函数:

public GetField();

答案 1

不能指定成员。你必须通过 getter 和 setter 来表明他们的存在,就像你一样。但是,您可以指定常量:

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

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


答案 2

延迟回答,但要获得此处所需的功能,您可能需要考虑包含字段的抽象类。抽象类将如下所示:

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

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


推荐