On 9 March 2021 22:15:49 GMT, "Kévin Dunglas" <ke...@dunglas.fr> wrote:
>Hi folks,
>
>Currently, it's not possible to use the ::class special constant with
>the
>constant() function. This doesn't work:
>
>var_dump(
>  constant('\DateTime::class')
>);


While this looks logical at first glance, I'm not sure this can actually work, 
because you are asking at runtime for information which only exists at compile 
time. This is similar to other "magic" constants such as __LINE__.

The only cases where ::class is calculated at runtime are self::class, and the 
recently added $obj::class, where $obj is an object instance. All other uses 
are expanded by the compiler based on the namespace and use statements in 
effect at that point in the code. If you try to calculate it at runtime, it 
would end up being evaluated where the call to constant() happens, which 
wouldn't actually have those namespace and use directives in effect.

Consider this example:


namespace Acme\Foo {
    use Some\Other\Baz;

    function test(string $class) {
        echo constant($class . '::class');
    }
}
namespace Acme\Different {
    use Acme\Bar\Baz as BarBaz;
    
    echo Baz::class, PHP_EOL;
    echo BarBaz::class, PHP_EOL;

    echo test('Baz');
    echo test('BarBaz');
}


Logically, the calls to test() should result in the same output as the direct 
use of "::class", but the call to constant() is in a different namespace, with 
different use statements. I'm not sure if use statements are even available at 
runtime, but if they were, there would be no way of knowing that the context of 
the call to test() should be used, not the context where it's defined.

Regards,
Hi Kevin,

-- 
Rowan Tommins
[IMSoP]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to