1

Is it possible in PHP, that an abstract class accesses a constant of the class below?

For example, can I factorize getName in Generic ?

abstract class Generic {
    abstract public function getName(): string;
}

class MorePreciseA extends Generic {
    private const NAME = "More Precise A";

    public function getName(): string {
        return self::NAME;
    }
}

class MorePreciseB extends Generic {
    private const NAME = "More Precise B";

    public function getName(): string {
        return self::NAME;
    }
}

Thanks

midnight
  • 25
  • 5
  • Doesn't matter it's abstract, there is no way for a parent class to know anything about a property of a child class (even if it wasn't private). Can you elaborate a bit more on what you're trying to achieve? Maybe we can suggest a different design. – El_Vanja Apr 25 '21 at 07:37

1 Answers1

3

This is where the difference between self:: and static:: comes in. More on that can be found here.

abstract class Generic {
    protected const NAME = "Generic";

    public function getName(): string {
        return self::NAME;
    }
}

class MorePreciseA extends Generic {
    protected const NAME = "More Precise A";
}

class MorePreciseB extends Generic {
    protected const NAME = "More Precise B";

}


$a = new MorePreciseA();
$b = new MorePreciseB();

var_dump($a->getName(), $b->getName());

Will result in

// string(7) "Generic"
// string(7) "Generic"

But if you replace the Generic implementation like so

abstract class Generic {
    public function getName(): string {
        return static::NAME;
    }
}

Then it will output

// string(14) "More Precise A"
// string(14) "More Precise B"
PtrTon
  • 3,705
  • 2
  • 14
  • 24