PHP, $this->{$var} -- 这是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16408037/
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 11:04:12  来源:igfitidea点击:

PHP, $this->{$var} -- what does that mean?

phpcodeigniter

提问by user1797484

I have encountered the need to access/change a variable as such:

我遇到了访问/更改变量的需要,如下所示:

$this->{$var}

The context is with CI datamapper get rules. I cant seem to find what this syntax actually does. What do the {'s do in this context? Why not just:

上下文与 CI 数据映射器获取规则有关。我似乎无法找到这个语法实际上做了什么。{ 在这种情况下做什么?为什么不只是:

$this->var

thanks!

谢谢!

回答by jszobody

This is a variable variable, such that you will end up with $this->{value-of-$val}.

这是一个可变变量,因此您将得到$this->{value-of-$val}.

See: http://php.net/manual/en/language.variables.variable.php

请参阅:http: //php.net/manual/en/language.variables.variable.php

So for example:

例如:

$this->a = "hello";
$this->b = "hi";
$this->val = "howdy";

$val = "a";
echo $this->{$val}; // outputs "hello"

$val = "b";
echo $this->{$val}; // outputs "hi"

echo $this->val; // outputs "howdy"

echo $this->{"val"}; // also outputs "howdy"

Working example: http://3v4l.org/QNds9

工作示例:http: //3v4l.org/QNds9

This of course is working within a class context. You can use variable variables in a local context just as easily like this:

这当然是在类上下文中工作的。您可以像这样轻松地在本地上下文中使用变量变量:

$a = "hello";
$b = "hi";

$val = "a";
echo $$val; // outputs "hello"

$val = "b";
echo $$val; // outputs "hi"

Working example: http://3v4l.org/n16sk

工作示例:http: //3v4l.org/n16sk

回答by Shoe

First of all $this->{$var}and $this->varare two very different things. The latter will request the varclass variable while the other will request the name of the variable contained in the string of $var. If $varis the string 'foo'then it will request $this->fooand so on.

首先$this->{$var}$this->var是两个非常不同的东西。后者将请求var类变量,而另一个将请求包含在$var. 如果$var是字符串,'foo'那么它将请求$this->foo等等。

This is useful for dynamic programming(when you know the name of the variable only at runtime). But the classic {}notation in a string context is very powerful especially when you have weird variable names:

这对于动态编程很有用(当您仅在运行时知道变量的名称时)。但是{}字符串上下文中的经典表示法非常强大,尤其是当您有奇怪的变量名时:

${'y - x'} = 'Ok';
$var = 'y - x';
echo ${$var};  

will print Okeven if the variable name y - xisn't valid because of the spaces and the -character.

Ok即使变量名y - x由于空格和-字符而无效,也会打印。