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
PHP, $this->{$var} -- what does that mean?
提问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->var
are two very different things. The latter will request the var
class variable while the other will request the name of the variable contained in the string of $var
. If $var
is the string 'foo'
then it will request $this->foo
and 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 Ok
even if the variable name y - x
isn't valid because of the spaces and the -
character.
Ok
即使变量名y - x
由于空格和-
字符而无效,也会打印。