Reputation: 180
We are trying to get name of variable passed i.e. "ClassName::CLASSCONSTANT" from
$this->TestFunction(ClassName::CLASSCONSTANT);
Function is like this:
function TestFunction() {
func_get_args();
// need ClassName::CLASSCONTANT as a string instead of its value
...
...
}
Upvotes: 2
Views: 63
Reputation: 37365
Do not mix data and metadata
It's an anti-pattern. No matter why do you need this - you can always avoid such solution. This is a bad practice - to try retrieve metadata by data. In your particular case - how could you know - may be there are several namespaces with same classes and constant inside them defined? Or may be there are even different constants in same class with same value.
So - you can not retrieve class name and constant name in common case by passed value. Thus, you should either pass that implicitly or reconsider your application's structure.
However, you can do that with:
class Foo
{
const A = 'ksdhfsdkjf';
const B = 'jkwjnsdf';
}
class Bar
{
const A = '2384sdkfj';
}
function baz($value)
{
$result = null;
foreach(get_declared_classes() as $class)
{
if(false !== ($const=array_search($value, (new ReflectionClass($class))->getConstants(), 1)))
{
$result = ['class'=>$class, 'const'=>$const];
break;
}
}
var_dump($result);
}
baz('jkwjnsdf');//array(2) { ["class"]=> string(3) "Foo" ["const"]=> string(1) "B" }
-but I definitely will not recommend that to use in any case.
Upvotes: 1