简体   繁体   中英

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM