2016-12-21 26 views
4

以下代碼有什麼區別?

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

回答

4

讀取$this對象的idkey屬性:

$this->idKey; 

讀取$this對象的可變屬性名(example在這種情況下),以便$this->example

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

同以上($this->example),但不太模糊(類似於添加括號來控制操作數o刻申,和有用的在某些情況下):

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

$這個 - > idKey

這是你將如何在PHP

Class Car{ 
//member properties 
var $color; 

    function printColor(){ 
    echo $this->color; //accessing the member property color. 
    } 
} 
訪問對象屬性

$ this - > $ idKey

這可以在屬性名本身存儲中使用的變量

$attribute ='color' 

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

$此 - > { '$ idKey'}

是一個明確的形式的上述表達式,但是它也服務於另一個目的,即訪問屬於的類的屬性不是 a valid variable name

$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