Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does $this->{$key} mean in PHP?

Tags:

php

What are the differences between following codes?

$this->idKey
$this->$idKey
$this->{$idKey}
like image 846
ZeroZerg Avatar asked Dec 24 '22 22:12

ZeroZerg


2 Answers

Reads the idkey property of the $this object:

$this->idKey;

Reads the variable property name of the $this object (example in this case) so $this->example:

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

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

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

A case where this may add clarity or control the order:

$this->{$idKey['key']};
$this->{$idKey}['key'];
like image 81
Alexander O'Mara Avatar answered Dec 26 '22 12:12

Alexander O'Mara


$this->idKey

This is how you would access an object property 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'}

Is an explicit form of above expression, but it also serves one more purpose, accessing properties of a class that is Not a valid variable name.

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

So you could use the curly brace expression to resolve this

$a = array('123' => '123', '123foo' => '123foo');
$o = (object)$a;
echo $o->{'123foo'}; // OK!
like image 26
Rahul Ravindran Avatar answered Dec 26 '22 11:12

Rahul Ravindran