J V
J V

Reputation: 11936

How to access a constant or static on a subclass in php

I want a class-wide variable that can be accessed from a parent class but isn't instantiated.

class A {
  abstract public static $v;
  public function v(){
    echo static::$v;
  }
}

class B extends A {
  $v = 'Hello world';
}

An abstract static or const would be perfect but of course they don't exist, and while I could implement this through an abstract function abstract functions can't be static either.

One way to do it would be to simply say:

protected $var = 'const';

And then never change it again. However, I'd like some more guarantees, and this needlessly uses some memory for every instance of the class.

Is there anything that could make this possible (And practical)?

I'd like:

  1. To declare it abstract so I can force subclasses to implement it
  2. To declare it static or const so that it's a property of the class not the instance
  3. To do it in a way that won't require jumping through a significant amount of hoops to implement or use

Upvotes: 0

Views: 116

Answers (1)

Siguza
Siguza

Reputation: 23850

abstract functions can't be static either.

They shouldn't, according to PHP5's "strict standards". But they sure can.

PHP 7 is totally fine with it.
PHP 5 complains, but that never stopped anyone only if Strict Standards are on, which is not the case by default.

That said, is there anything wrong with using any old abstract, non-static method?
The following code works just fine.

abstract class A
{
    public abstract function actualV();

    public function v()
    {
        echo $this->actualV();
    }
}

class B extends A
{
    public function actualV()
    {
        return 'const';
    }
}

(new B())->v(); will echo const.

And if a class does not implement actualV:

Fatal error: Class C contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (A::actualV).

If you really really want to, you can slap a static in front of the actualV method declaration, change $this->v() to static::v() and disable strict standards (if they're on and you're using PHP 5) with error_reporting(E_ALL & ~E_STRICT);, and everything will still work just the same.

Upvotes: 1

Related Questions