Ben Edwards Ben Edwards - 2 years ago 64
PHP Question

How do I force derived classes to include a static property?

How can I enforce the rule that derived classes should contain some static property or value?

in this example I'm looking to ensure that every class which extends Parent should contain a static variable $foo

abstract class Parent{
// Trying to enforce that all derived classes must contain a static $foo;
static protected $foo;

public function getFoo(){
return get_class($this)::$foo;
}

}

class Child extends Parent{
static protected $foo = 0;
}

Answer Source

You cannot abstract a class property however in this case it is probably better to do the following:

abstract class Parent{      
    abstract public function getFoo();
}

class Child extends Parent{
    private $foo = 0;

    public function getFoo(){
        return $this->foo;
    }
}

As an additional note for you to know in the future where you did get_class($this)::$foo that is not necessary and you can just do static::$foo which works the same.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download