PHP 接口(interface) : Specify ANY visibility

标签 php oop interface abstract

我正在为一组类使用一个接口(interface)。但是我有一个问题,因为我希望任何 visibility在接口(interface)中被允许(即:publicprotectedprivate)。

我只需要保护父方法,我需要私有(private)子方法,但我收到错误提示

Fatal error: Access type for interface method Baz::qux() must be omitted in <the file with Baz/Bar>."

我尝试在接口(interface) Baz 中指定其他可见性方法并删除 public,但都失败了。

有什么方法可以通过界面实现吗?如果没有,那么有没有办法可以声明它abstract,我也尝试过,但失败了。

interface Baz
{
    public function qux();
}

class Bar implements Baz
{
    protected function qux()
    {
        //do foo
    }
}

class Foo extends Bar implements Baz
{
    private function qux()
    {
        parent::qux();
    }
}

最佳答案

您在 Interfaces 中声明的方法应该是公开的。你定义一个带有接口(interface)的契约。任何非公共(public)方法都是实现细节,不属于接口(interface)。顾名思义,实现细节应该进入具体的类实现接口(interface)。

来自维基百科:

Programming to the interface

The use of interfaces allows a programming style called programming to the interface. The idea behind this is to base programming logic on the interfaces of the objects used rather than on internal implementation details. Programming to the interface reduces dependency on implementation specifics and makes code more reusable.[7] It gives the programmer the ability to later change the behavior of the system by simply swapping the object used with another implementing the same interface.

关于PHP 接口(interface) : Specify ANY visibility,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12898397/

相关文章:

php - CURLOPT_FOLLOWLOCATION 不能在启用 safe_mode 或在

java - 生成方法中无法识别变量

oop - OO - 继承与装饰问题

java - 对子对象的引用数组初始化失败

java - 如何简化多个相同的枚举?

php - 获取 mime 类型的压缩文件

php - MySQL : auto update date on select row

c# - 将合约添加到接口(interface)实现

php - 使用 PHP 伪造 URL 中的路径部分?

Java接口(interface): compiler error