views:

88

answers:

1

Hey guys,

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?

+1  A: 

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