【问题标题】:interface declaration in PHP - why do declarations get mixed?PHP中的接口声明 - 为什么声明会混淆?
【发布时间】:2016-11-19 21:16:41
【问题描述】:

我正在尝试为我的类声明接口,如下所示:

namespace Helpers\Interfaces {
    interface Cache {
        public static function getInstance($profile = null);
    }
}

然后我像这样应用它们:

namespace Helpers {
    class Cache implements Interfaces\Cache {
        public static function getInstance($profile = null) {
            /* ... */
        }
    }
}

到目前为止,一切都很好(显然,至少)。我遇到的问题是 NetBeans 给了我一个错误,指出我的类不是抽象的并且没有实现某个方法。

该方法属于我创建的一个对象,用于收集操作某些方法所需的配置参数,而不根据对象提供特定的配置选项(如主机、端口、API 密钥等)。

在这个例子中,这个方法被称为\Configuration\Helpers\Cache::getConfiguration($profile);

冲突的声明来自这个接口:

namespace Configuration\Helpers\Interfaces {
    interface Cache {
        public static function getConfiguration($profile = null);
    }
}

应用如下:

namespace Configuration\Helpers {
    class Cache implements Interfaces\Cache {
        public static function getConfiguration($profile = null) {
            /* ... */
        }
    }
}

它有效地混合了接口,尽管它们是命名空间的! 我要注意的是接口和实现此类接口的类声明始终在同一个文件中,每个对象一个文件。

NetBeans 8.2 上的 PHP 版本是 7.0.13。

我做错了什么?

【问题讨论】:

    标签: php interface namespaces


    【解决方案1】:

    您的接口和类位于不同的命名空间中。您可能需要在您的类中添加一个 use 语句。例如,您可以添加:使用 Helpers\Interfaces 作为接口。这一行可以超越类定义:class Cache implements Interfaces\Cache。

    另请参阅:http://php.net/manual/en/language.namespaces.definitionmultiple.php

    【讨论】:

    • 我试试看。感谢您的提示:)
    • 不,它不会使错误通知消失。但是,我怀疑它与 NetBeans 而不是我的编码风格有关,因为我在执行代码时没有任何警告或错误,它只是 NetBeans 抱怨声明......
    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多