Search code examples
phpoopinterfaceconstantslate-static-binding

Interface constants, Late Static Bindings


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;
    }

}

Does it matter if you use self or static considering that interface constants can't be overridden by a class/interface that inherits them?


Solution

  • It could matter, because even if you can't override interface constants in classes implementing an interface, you can override these constants in classes extending the class that originally implemented the interface:

    E.g. the following:

    <?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';
    }
    

    Now this:

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

    would output passwords.reset.

    But this:

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

    would output foobar.

    But if you didn't use late static binding, and used self, you'd get passwords.reset every time.

    See it working here.