[英]How can we get variable name used in function call?
We are trying to get name of variable passed ie "ClassName::CLASSCONSTANT" from 我们正在尝试从中获取传递的变量名称,即“ ClassName :: CLASSCONSTANT”
$this->TestFunction(ClassName::CLASSCONSTANT);
Function is like this: 功能是这样的:
function TestFunction() {
func_get_args();
// need ClassName::CLASSCONTANT as a string instead of its value
...
...
}
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. -但我绝对不建议在任何情况下使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.