php - 接口(interface)常量、后期静态绑定(bind)

标签 php oop interface constants late-static-binding

interface PasswordBrokerContract
{
    const PASSWORD_RESET = 'passwords.reset';

    public function reset(array $credentials, Closure $callback);
}

class PasswordBroker implements PasswordBrokerContract
{
    public function reset(array $credentials, Closure $callback)
    {
        // implementation

        return static::PASSWORD_RESET;
    }

}

考虑到接口(interface)常量不能被继承它们的类/接口(interface)覆盖,使用 self 或 static 是否重要?

最佳答案

这可能很重要,因为即使您无法覆盖实现接口(interface)的类中的接口(interface)常量,您也可以在扩展最初实现该接口(interface)的类的类中覆盖这些常量:

例如以下内容:

<?php

interface Contract
{
    const PASSWORD_RESET = 'passwords.reset';
    public function reset(): void;
}


class A implements Contract
{
    public function reset(): void
    {
        echo static::PASSWORD_RESET, "\n";
    }
}

class B extends A {
    const PASSWORD_RESET = 'foobar';
}

现在这个:

(new A())->reset();

将输出passwords.reset

但是这个:

(new B())->reset();

将输出foobar

但是如果您没有使用后期静态绑定(bind),而是使用了 self,那么您每次都会得到 passwords.reset

查看它的工作情况 here .

关于php - 接口(interface)常量、后期静态绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59067186/

相关文章:

javascript - 每分钟获取 PHP 变量

php - Joomla 3.0 DS 不工作(使用未定义常量 DS)

php - 如何使PHP中的数组打印唯一?

c++ - 避免文件导出器中基于节点的文件类型的依赖 hell ?

c# - 模拟 'System.Console' 行为

c# - 动态加载 DLL 中的接口(interface)

php - 如何编写一个函数来告诉我当前正在查看主页(/index.php)?

C++接口(interface)设计——IO板底层协议(protocol)

javascript - WKWebView 不支持 JavaScript 类

Java 重写方法丢弃异常