phpclassstaticabstractfactorization

PHP abstract class access of constant below


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


Solution

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