What does $ this & # 8594; mean {$ key} in PHP?

What is the difference between the following codes?

$this->idKey
$this->$idKey
$this->{$idKey}
+4
source share
3 answers

Reads an idkeyobject property $this:

$this->idKey;

Reads the property name of an object variable $this( examplein this case), therefore $this->example:

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

Same as above ( $this->example), but with less uncertainty (similar to adding parentheses to control the order of operands and useful in some cases):

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

A case where this can add clarity or control order:

$this->{$idKey['key']};
$this->{$idKey}['key'];
+5
source

$ this-> IdKey

This is how you would get access to the property of an object in php

class Car {
 //member properties
 var $color;

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

$ this-> $ IdKey

This can be used when the property name itself is stored in a variable.

$attribute ='color'

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

$this-> { '$ IdKey'}

, , , .

$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!
+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

+1

Source: https://habr.com/ru/post/1664371/


All Articles