In php, is there any way to determine whether ::class was used when generating a string?

Tags: , , ,

The two following return statements will return the same string:

getClassName(): string
    return MyClassName::class; // returns 'MyClassName'
    return 'MyClassName';      // returns 'MyClassName'

We also have code that calls this method.

$className = getClassName();

In our code which calls this method, is there any way to determine whether ::class was used to generate the string?

IDE’s that we use are able to detect when ::class is being used, and we would like to somehow use this logic in our code at compile time.


IDEs can look at the source code and see what syntax you’re using. They use this to provide hints, cross references, and all the other nice things they do while you’re editing.

But once the code is compiled and running, most of this information is discarded. Values don’t have any information about how they were calculated — a string is just a bunch of characters. There are reflection features that allow you to access the call stack to see what functions were invoked, since this is needed in memory to implement returning, but data doesn’t keep a trace of where the values came from.

So there’s no built-in way to get the information you’re looking for. If you need to keep track of this, you’ll have to implement it in the application code itself.

getClassName(): array
    return ['source' => '::class', 'value' => MyClassName::class];
    return ['source' => 'string', 'value' => 'MyClassName'];

Source: stackoverflow