php php中的动态类属性$$value

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/854231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:06:36  来源:igfitidea点击:

dynamic class property $$value in php

phpclassdynamicvariablesproperties

提问by Cameron A. Ellis

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?

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

回答by Antonio Haley

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

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

echo $this->$string;

回答by Rick

If you want to use a property value for obtaining the name of a property, you need to use "{" brackets:

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

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

Even if they're objects, they work:

即使它们是对象,它们也能工作:

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

回答by Matthew H.

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

正如其他人所提到的, $this->$string 应该可以解决问题。

However, this

然而,这

$this->$$string;

will actually evaluate string, and evaluate again the result of that.

将实际评估字符串,并再次评估其结果。

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

回答by Mike Stanford

you were very close. you just added 1 extra $ sign.

你非常接近。您刚刚添加了 1 个额外的 $ 符号。

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

回答by Marc W

echo $this->$string; //should work

You only need $$stringwhen accessing a local variable having only its name stored in a string. Since normally in a class you access it like $obj->property, you only need to add one $.

$$string在访问仅将其名称存储在字符串中的局部变量时才需要。因为通常在一个类中您可以像访问它一样$obj->property,所以您只需要添加一个$.

回答by Marc W

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

要记住确切的语法,请记住您使用的 a$比通常使用的多。当您$object->property用来访问对象属性时,动态访问是通过$object->$property_name.