简体   繁体   English

没有任何方法使用界面有什么好处? 在PHP中

[英]What are the benefits of using interface without any methods ? In php

AS I was looking at code in Laravel 5 project, I encountered with a class Like below -- 当我在Laravel 5项目中查看代码时,遇到类似下面的类 -

class Abc extends Command implements SelfHandling, ShouldBeQueued
{

}

And where Interfaces are like below - 接口如下所示 -

interface SelfHandling {}
interface ShouldBeQueued {}

I got confused if it does not have any methods then what's the use of these interfaces ? 如果它没有任何方法,我会感到困惑,那么这些接口的用途是什么?

It allows to handle objects by behavior. 它允许按行为处理对象。 Say you have an array of objects implementing different interface, you can then differentiate them doing this : 假设您有一组实现不同界面的对象,您可以将它们区分开来:

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

This example is a bit crude, but I hope it will help you. 这个例子有点粗糙,但我希望它会对你有所帮助。

They are used as sort of a "flag". 它们被用作一种“旗帜”。 It can be checked by doing $command instanceof ShouldBeQueued . 可以通过执行$command instanceof ShouldBeQueued来检查它。

The alternative would be to include a method, but that would require multiple lines of redundant code. 另一种方法是包含一种方法,但这需要多行冗余代码。 (Most implementations would return true anyway.) (无论如何,大多数实现都会返回true 。)

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

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

Checking it would be a bit more complicated as well: 检查它会更复杂一点:

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

Whether it is a good practice is another matter. 这是一个好的做法是另一回事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM