现在我正试图为自己的客户开发一个php框架。在我的应用程序中,我想将$instance->propertyName
作为参数传递。但不需要$instance->propertyName
值。只有我想使用propertyName部分作为字符串值。我可以将propertyName作为字符串吗?
例如,如果我有一个类的对象$bar
class foo
{
public $someProperty1;
public $someProperty2;
}
$bar = new foo();
如果我有其他类似的课程
class anotherClass
{
public function someMethod($arg)
{
//I need the property name that provide the $arg value in this place
}
}
当我运行这个代码时
$someObject = new anotherClass();
$someObject->someMethod($bar->someProperty1); //I want to know the name of property that provide a value to the someMethod method (the 'someProperty1' in this case)
那么我想知道anotherClass
类中的方法someMethod
中提供$arg
值的属性的名称。作为上面例子的结果,我想要得到一个字符串someProperty1
。
function foo($bar)
{
//here you want to know the name of the variable that passing the value
}
$x = 5;
$y = 5;
foo($x); //here you want to know the name 'x' of the variable
foo($y); //here you want to know the name 'y' of the variable
在这两种情况下,函数将只获得有关值5
的信息,而不提供有关变量名称的信息。
如果你想知道为方法提供值的变量(或对象属性)的名称,那么你可以使用非常低效的东西,比如这个
class someClass
{
public $someProperty;
}
class otherClass
{
public function setSomething($arg)
{
$trace = debug_backtrace();
$vLine = file($trace[0]['file']);
$fLine = $vLine[$trace[0]['line'] - 1];
preg_match("/(.*?)'((.*?)->(.*?)')/i", $fLine, $match);
var_dump($match[3], $arg);
}
}
$t = new someClass();
$t->someProperty = 5;
$o = new otherClass();
$o->setSomething($t->someProperty);
setSomething
方法中的var_dump
将返回属性的名称和值
string(12)"someProperty"int(5)
这个解决方案是基于这篇文章的想法https://stackoverflow.com/a/404637/4662836