2
votes

I'm trying to get the value of a constant of an extending class, but in a method of the abstract class. Like this:

    abstract class Foo {
        public function method() {
            echo self::constant;
        }
    }

    class Bar extends Foo {
        const constant = "I am a constant";
    }

    $bar = new Bar();
    $bar->method();

This however results in a fatal error. Is there any way to do this?

2

2 Answers

3
votes

This is not possible. A possible solution would be to create a virtual method that returns the desired value in the subclasses, i.e.

abstract class Foo {
  protected abstract function getBar();

  public function method() {
    return $this->getBar();
  }
}

class Bar extends Foo {
  protected function getBar() {
    return "bar";
  }
}
3
votes

This is possible using the Late Static Binding keyword introduced in PHP 5.3

Essentially, self refers to the current class that the code is written in, but static refers to the class the code is running from.

We could rewrite your code snippet as:

abstract class Foo {
    public function method() {
        echo static::constant;    // Note the static keyword here
    }
}

class Bar extends Foo {
    const constant = "I am a constant";
}

$bar = new Bar();
$bar->method();

However, this pattern of coding is dirty and you should probably instead introduce a protected api between your parent class and subclasses to funnel that kind of information back and forth.

So from a code organization perspective, I would lean more towards the solution that Morfildur put forward.