gpt4 book ai didi

PHP 接口(interface) : Specify ANY visibility

转载 作者:IT王子 更新时间:2023-10-28 23:46:32 24 4
gpt4 key购买 nike

我正在为一组类使用一个接口(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com