PHP question regarding constant()

Hey there,
just some background info needed for my learning curve …


namespace Something;

use DeviceDetector\Parser\Device\DeviceParserAbstract;

// Some code ...

class Someclass {
    protected function setVersionTruncation($version)
        $string = strtoupper($version);
        $constant = 'DeviceDetector\Parser\Device\DeviceParserAbstract::VERSION_TRUNCATION_' . $string;

        if (defined($constant)) {
            return DeviceParserAbstract::setVersionTruncation(constant($constant));
        } else {
            return false;

Question: Why does constant need the full namespace & (abstract) class DeviceParserAbstract while the return statement doesn’t?

Thank you very much.

If you use the constant’s name literally (without quotes), the class is resolved with the use statement at the top (just like with static methods etc.).

Functions like the defined() function that take a string instead can’t resolve classes based on use statements as they don’t have the necessary context.

You can however dynamically get the full class name including namespace using:

$constant = DeviceParserAbstract::class . '::VERSION_TRUNCATION_' . $string;
1 Like

Thank you very much, kind Sir!