English 中文(简体)
PHP中的动态类属性$$value。
原标题:
  • 时间:2009-05-12 18:45:12
  •  标签:

How can i reference a class property knowing only a string?

class Foo
{
    public $bar;

    public function TestFoobar()
    {
        $this->foobar( bar );
    }

    public function foobar($string)
    {
         echo $this->$$string; //doesn t work
    }
}

评估字符串的正确方法是什么?

最佳回答

当引用对象的成员变量时,您只需要使用一个$符号和一个字符串变量。

echo $this->$string;
问题回答

如果您想使用属性值来获取属性名称,则需要使用“{”括号:

$this->{$this->myvar} = $value;

即使它们是物品,它们依然拥有作用。

$this->{$this->myobjname}->somemethod();

As the others have mentioned, $this->$string should do the trick.

然而,这

$this->$$string;

将实际评估字符串,并重新评估其结果。

$foo =  bar ;
$bar =  foobar ;
echo $$foo; //-> $ bar  ->  foobar 

你非常接近了。你只是多添加了一个美元符号。

public function foobar($string)
{
     echo $this->$string; //will work
}
echo $this->$string; //should work

只有当访问本地变量时,需要使用$$string,而该变量仅在字符串中存储其名称。由于通常在类中访问它时,您可以像$obj->property这样访问它,因此只需要添加一个$

To remember the exact syntax, take in mind that you use a $ more than you normally use. As you use $object->property to access an object property, then the dynamic access is done with $object->$property_name.





相关问题
热门标签