Home > Mobile >  how to declare a abstract const in php
how to declare a abstract const in php

Time:08-02

I found this post where @WebSmithery user uses a clever 'hack' to solve this problem. Abstract constants in PHP - Force a child class to define a constant

In that post, @WebSmithery posted an working example. see below:

<?php

abstract class Foo {

    // Self-referential 'abstract' declaration
    const NAME = self::NAME;

}

class Fooling extends Foo {

    // Overrides definition from parent class
    // Without this declaration, an error will be triggered
    const NAME = 'Donald';

}

$fooling = new Fooling();

echo $fooling::NAME;

While the above example works fine, I did find a problem with it. It turns out that this 'hack' will fail if the abstract class has code to access the const (NAME in this case) itself. Below is an example. When I run it, it throws this error "Cannot declare self-referencing constant". Wonder if there is a way to get around this?

<?php

abstract class Foo
{

    // Self-referential 'abstract' declaration
    const NAME = self::NAME;

    public function echoNAME()
    {
        echo Foo::NAME;
    }
}

class Fooling extends Foo
{

    // Overrides definition from parent class
    // Without this declaration, an error will be triggered
    const NAME = 'Donald';
}

$fooling = new Fooling();

$fooling->echoNAME();

CodePudding user response:

If you want to refer to a static member of a child class, you need to use late static bindings.

So instead of Foo:NAME, you would use static::NAME.

<?php

abstract class Foo
{
    
    // Self-referential 'abstract' declaration
    const NAME = self::NAME;
    
    public function echoNAME()
    {
        echo static::NAME;
    }
}

class Fooling extends Foo
{
    
    // Overrides definition from parent class
    // Without this declaration, an error will be triggered
    const NAME = 'Donald';
}

$fooling = new Fooling();

$fooling->echoNAME();
echo PHP_EOL;
  •  Tags:  
  • php
  • Related