Php 强制实现接口的类定义常量

Php 强制实现接口的类定义常量,php,oop,inheritance,interface,Php,Oop,Inheritance,Interface,我愿意强制我的类定义一个常量命名命令。如果php允许从中的接口重写常量,则 class RequestInterface { const COMMAND = "no-command-specified"; } class LoginRequest implements RequestInterface { const COMMAND = "loginuser"; public $username; public $password; } $request =

我愿意强制我的类定义一个常量命名命令。如果php允许从中的接口重写常量,则

class RequestInterface
{
    const COMMAND = "no-command-specified";
}

class LoginRequest implements RequestInterface
{
    const COMMAND = "loginuser";
    public $username;
    public $password;
}

$request = new LoginRequest();
$request->username = "user";
$request->password = "blah";
显然,这是行不通的。我正在寻找一种干净的方法来让我的请求定义commandcosntant

我一直在考虑以下选择:

  • 接口定义了一个getCommand方法,我的请求类需要实现它并以字符串形式返回命令名。但是每个请求的代码太多了
  • 用抽象类替换接口。这看起来很奇怪,因为抽象类通常至少要定义一个方法
  • 接口成为抽象类并定义受保护的变量$command。它还有一个getter方法,返回$this->command;。子项重写受保护的属性$command。我不喜欢将公共变量(应该是变量)与保护变量混合的方式,保护变量实际上不应该是可修改的,因此一开始就不应该是变量

    class LoginRequest extends BaseRequest
    {
         protected $command = "loginuser";
         public $username;
         public $password;
    }
    

实现这一目标最干净的方法是什么?

就我个人而言,我的选择是:

interface RequestInterface
{
    /**
     * @returns string
     */
    public function getCommand();
}

class LoginRequest implements RequestInterface
{
    public function getCommand() {
        return "loginuser";
    }
   ...
}

您可以随时检查返回的字符串是否包含
is\u string()
。无论如何,没有什么可以阻止某人将命令设置为数字。

您所说的“每个请求的代码太多”是什么意思?您想避免在实现类中定义接口的方法吗?我可能会使用这个选项。在过去,我也使用了第二个(抽象类)选项,但我同意没有任何定义的方法是不寻常的。如果一个类只有常量,那么您在当前类中引用的是什么?这样你总是有一个常数central@MichaelBerkowski我希望我的请求对象是最简单的数据容器。我很欣赏这种方法似乎是最干净的,但在我看来,定义一种方法似乎有点过分了code@user3790680这种方法集中了数据,但没有以任何方式强制执行,我知道,但我认为强制执行是确保获得正确数据的一部分。实际上,它对强制执行没有帮助。如果您想将其用作序列化对象,请查看
JsonSerializable
接口。然后可以定义返回的数据。