PHP静态方法是否可以合法地具有受保护或私有的可见性?

14

我意识到在PHP中可以将静态类方法定义为私有或受保护的。这使得已实例化的类或公共静态方法可以访问其自身的私有/受保护静态方法。

protected static function jumpOver  ()

但是我不确定这在面向对象设计上是否合法。我找不到任何真实的信息表明这样做是可以的。如果这不是有效的方法,我担心PHP可能会在将来的版本中"修补"它并破坏我的脚本。


2
“protected static function” 是合法的,它可以作为其他静态方法的辅助方法使用。 - d.raev
2个回答

10

没问题。静态方法通常只是帮助方法,其中可能包含您不希望公开的代码。

我能想到的其他常见面向对象语言也有这个功能(C ++、Java、C#)。我真的不认为他们会删除该功能。

此外,PHP的开发人员很慢地破坏现有的功能,所以我不会太担心。


嗯...你想用的不是final关键字来保护你的代码吗? - dierre
4
final关键字可以防止被子类重写或继承,但它并不能保护访问权限。 - zneak
哦,好的。对不起我以为“有可能不想公开的代码”指的是可能要进行覆盖或继承它的可能性。 - dierre
其他语言也有同样的好理由:正如@d.raev所指出的那样,它可以用来保护那些你不想暴露的其他public static方法使用的方法。 - XedinUnknown

0
如同Linus在他的智慧中建议我们的那样,让我们来看一些代码。
比方说,你有一个"static"类(并不是真实存在的东西):
class MyClass
{
    public static function doThing(): void
    {
        // Do something
    }
}

现在,假设你想要添加另一种方法,它与第一个方法有一些相同的逻辑:
class MyClass
{
    public static function doThing(): void
    {
        // Do something
        // Then, do this particular thing
    }

    public static function doOtherThing(): void
    {
        // Do something else
        // Then, do the same particular thing
    }
}

有道理的是,将doThing()doOtherThing()中相同的特定事物提取到一个独立的方法中,对吧?
class MyClass
{
    public static function doThing(): void
    {
        // Do something
        static::doParticularThing();
    }

    public static function doOtherThing(): void
    {
        // Do something else
        static::doParticularThing();
    }

    public static function doParticularThing(): void
    {
        // Some more generic or repetitive logic
    }
}

太好了!现在MyClass的消费者也可以开始使用doParticularThing()了。就像任何其他公共API一样,这可能会导致一种情况,即您删除该方法,因为您的其他逻辑不再依赖它,并且破坏了所有使用doParticularThing()的消费者。他们会来创建问题跟踪器中的问题。假设您不希望发生这种情况:
class MyClass
{
    public static function doThing(): void
    {
        // Do something
        static::doParticularThing();
    }

    public static function doOtherThing(): void
    {
        // Do something else
        static::doParticularThing();
    }

    protected static function doParticularThing(): void
    {
        // Some more generic or repetitive logic
    }
}

现在你有一个其他代码可以使用的类来执行doThing()doOtherThing(),但它们不会受到你可能稍后更改或删除的doParticularThing()的影响。这是良好的API设计,如果你正确地使用这种方法,你的用户将会感谢你。

也要感谢@d.raev,他在评论中首先提到了这一点。但是那条评论并不太显眼,我觉得这个观点需要一个能被接受为答案的表达方式。 - XedinUnknown
此外,在我的例子中,MyClass的消费者可以根据需要更改doParticularThing()方法的工作方式,而不影响其他方法。这部分是因为受保护成员确实是protected而不是private,并且没有使用final关键字。但也因为doParticularThing()是用static而不是self调用的:这确保了继承的doThing()doOtherThing()调用被覆盖的方法,而不是MyClass的方法。 - XedinUnknown

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接