$ this-> {$ key}在PHP中意味着什么?

时间:2016-12-21 03:56:23

标签: php

以下代码之间有什么区别?

$this->idKey
$this->$idKey
$this->{$idKey}

3 个答案:

答案 0 :(得分:5)

读取idkey对象的$this属性:

$this->idKey;

读取$this对象的变量属性名称(在本例中为example),以便$this->example

$idKey = 'example';
$this->$idKey;

与上面($this->example)相同,但模糊性较小(类似于添加括号来控制操作数顺序,在某些情况下很有用):

$idKey = 'example';
$this->{$idKey};

答案 1 :(得分:1)

  

<强> $这 - &GT; idKey

这是你在php中访问对象属性的方法

Class Car{
 //member properties
 var $color;

  function printColor(){
    echo $this->color; //accessing the member property color.
  }
}
  

<强> $这 - &GT; $ idKey

当属性名称本身存储在变量

中时,可以使用此选项
$attribute ='color'

$this->$attribute // is equivalent to $this->color
  

<强> $这 - &GT; { '$ idKey'}

是上述表达式的一种显式形式,但它还有另一个目的,即访问 a your terminal isn't configured correctly的类的属性。

$a = array('123' => '123', '123foo' => '123foo');
$o = (object)$a;
echo $o->123foo; // error

因此,您可以使用花括号表达式来解决此问题

$a = array('123' => '123', '123foo' => '123foo');
$o = (object)$a;
echo $o->{'123foo'}; // OK!

答案 2 :(得分:1)

$this->idKey是作用域对象的属性idKey

$this->$idKey$this->{$idKey}将为您提供访问以$idKey值命名的属性的相同结果。

class ButtHaver{
    public idKey;
    public buttSize;
}

$b = new ButtHaver();
$b->idKey = 'buttSize';
$b->buttSize = 'Large';
echo $b->idKey; // outputs 'buttSize'
echo $b->$idKey; // outputs 'Large'
echo $b->{$idKey}; // outputs 'Large'

${$}语法用于解决$$a[1]等特定情况下的歧义,以清除您想要的变量。 ${$a[1]}表示数组中值的变量,${$a}[1]表示变量$ a中命名的数组。

您可以在此处阅读所有相关信息:http://php.net/manual/en/language.variables.variable.php

相关问题