2015-04-21 18 views
1

我可以使用對象/數組的值來直接定義另一個對象/數組的值嗎?如何在同一個對象內設置另一個相同值的對象的值

說明

我知道這不是要做到這一點適當的方式,但我試圖不同的方式和令人沮喪......

代碼中,我已經試過:

$object= (object)array(
    'akey'=>'value', 
    'anotherkey'=>'anothervalue', 
    'the_key_of_interested_special_value'=>$this->data_evento 
); 
var_dump($object); 

而且它會引發一個致命錯誤:

Fatal error: Using $this when not in object context on line 4

我不想使用外部變量/ arr ay/object和/或函數在數組/對象定義之外。

我已經知道我可以做這樣的事情:

$object= (object)array(
    'akey'=>'value', 
    'anotherkey'=>'anothervalue' 
); 
$object->the_key_of_interested_special_value = $object->akey.'_correct'; 

var_dump($object); 

var_dump($object); 

其結果將是(這是結果id'like獲得無外部。定義):

object(stdClass)#1 (3) { 
    ["akey"]=> 
    string(5) "value" 
    ["anotherkey"]=> 
    string(12) "anothervalue" 
    ["the_key_of_interested_special_value"]=> 
    string(17) "value_correct" 
} 
+1

你認爲'$ this'指的是'$ object'? – Ghost

+0

我不認爲對象內部的「遞歸」對象分配會起作用 – pbaldauf

+0

@Ghost是的我想引用對象所以我可以達到我的目標!:D –

回答

2

您可以使用僅在對象上下文中使用$this。你要做的就是

  1. 創建一個數組
  2. 將其轉換爲一個對象

僞變量$ this可以在當一個方法在對象內部調用。 $這是給調用對象的引用(通常是該方法所屬的對象,但可能的另一種對象,如果該方法是從第二個對象的上下文靜態調用)。」 http://php.net/manual/en/language.oop5.basic.php

+0

你可以給我一個PHP代碼段嗎? –

相關問題