What are the differences between following codes?
$this->idKey
$this->$idKey
$this->{$idKey}
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'];
$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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With