Php实例属性名称为字符串作为方法参数

时间:2016-07-26 19:53:57

标签: php oop properties

现在我正在尝试为自己的客户开发一个php框架。在我的应用中,我想传递$instance->propertyName作为参数。但是,不需要$instance->propertyName价值。只有我想将propertyName部分用作字符串值。我可以将 propertyName 作为字符串吗?

例如,如果我有一个类<{p>}的对象$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)

然后我想在someMethod类中的方法anotherClass内知道提供$arg值的属性的名称。作为上面的结果,我想得到一个字符串someProperty1

1 个答案:

答案 0 :(得分:0)

没有简单的方法来实现这个目标。你想知道这样的事情

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的信息,而关于变量名称的nothig将提供值。

如果你想知道为方法提供价值的变量(或对象属性)的名称,那么你可以使用非常低效这样的东西

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);

var_dump方法中的setSomething将返回名称和属性值

  

string(12)&#34; someProperty&#34; INT(5)

此解决方案基于此帖https://stackoverflow.com/a/404637/4662836

的想法