【问题标题】:What are the benefits of using interface without any methods ? In php在没有任何方法的情况下使用接口有什么好处?在php中
【发布时间】:2016-12-15 08:27:17
【问题描述】:

当我在 Laravel 5 项目中查看代码时,我遇到了一个类 如下--

class Abc extends Command implements SelfHandling, ShouldBeQueued
{

}

接口如下所示 -

interface SelfHandling {}
interface ShouldBeQueued {}

如果它没有任何方法,我会感到困惑,那么这些有什么用 接口?

【问题讨论】:

标签: php class laravel-5 interface multiple-inheritance


【解决方案1】:

它允许通过行为来处理对象。假设您有一组实现不同接口的对象,然后您可以这样做区分它们:

if($obj instanceof ShouldBeQueued){
    //do something
}
else if{$obj instanceof SelfHandling){
    //do something else
}

这个例子有点粗略,但希望对你有所帮助。

【讨论】:

  • 那么如果我创建一个 Abc 类的实例应该是什么情况,它可以同时是 ShouldBeQueued 和 SelfHandling 的实例吗?那么 if 和 else if 没有任何意义,因为它在这两种情况下都会出现?
  • 请记住,这只是一个粗略的例子。但是,您可以拥有实现一个、两个或一个都不实现此接口的对象并相应地处理它们。
  • 有人想出了比我更好的答案:wpkrauts.com/2013/how-to-build-flexible-php-interfaces/…。在你的情况下,我认为这是为了使用内部类型
【解决方案2】:

它们被用作某种“标志”。可以通过$command instanceof ShouldBeQueued进行检查。

另一种方法是包含一个方法,但这需要多行冗余代码。 (无论如何,大多数实现都会返回true。)

interface ShouldBeQueued
{
    /**
     * @return bool
     */
    function shouldBeQueued();
}

class Abc extends Command implements ShouldBeQueued
{
    function shouldBeQueued()
    {
        return true;
    }
}

检查它也会有点复杂:

if ($command instanceof ShouldBeQueued && $command->shouldBeQueued()) { /*...*/ }

这是否是一个好的做法是另一回事。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 2023-01-04
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    • 2021-02-21
    • 1970-01-01
    相关资源
    最近更新 更多