Search code examples
phpconstantsabstract-class

Accessing class constant from abstract method in PHP5


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?


Solution

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