php中的动态类属性$$value

2022-01-02 00:00:00 class variables dynamic properties php

如何引用只知道字符串的类属性?

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
    }
}

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

what is the correct way to eval the string?

推荐答案

当使用字符串变量引用对象的成员变量时,只需使用一个 $.

You only need to use one $ when referencing an object's member variable using a string variable.

echo $this->$string;

相关文章