2014-01-06 15 views
0

這工作得很好:PHP新手:不能用恆定的定義陣列

$entity->field_time[LANGUAGE_NONE][0] = array(
    'value' => date_format($date), 
    'timezone' => 'UTC', 
); 

但我需要使它更通用,允許不同的字段名稱。所以,我嘗試使用常數:

define('FIELD_TIME', 'field_time'); 
$entity->FIELD_TIME[LANGUAGE_NONE][0] = array(
    'value' => date_format($date), 
    'timezone' => 'UTC', 
); 

但這並不定位正確的數組名,這應該是[field_time] [LANGUAGE_NONE] [0]

我也試過:

define('FIELD_TIME', 'field_time'); 
$entity->constant('FIELD_TIME')[LANGUAGE_NONE][0] = array(
    'value' => date_format($date), 
    'timezone' => 'UTC', 
    ); 

但是,拋出:解析錯誤:語法錯誤,意外'['

我在做什麼錯?

+1

「常量的值聲明數組;只有標和允許空值標值是整數,浮點數,字符串或布爾值。可以定義資源常量,但不建議這樣做,並可能導致不可預知的行爲。「 – Flosculus

+0

@Flosculus他不想使用常量作爲數組,但它是值。假設你有一個帶有property(array)='public $ _arr = array(...);'和另一個文件define('BLA','_arr');'的類。 OP想要做'$ obj - > _ arr = ...'但是使用常數值=>'$ obj-> BLA =' –

+0

如果'FIELD_TIME'是類的常量,不應該像' EntityClass :: FIELD_TIME'? – Flosculus

回答

1

試試這個

$entity->{FIELD_TIME}[LANGUAGE_NONE][0] = 'something'; 

是的,只是括號不斷!這也適用於函數調用

$entity->{FUNC_NAME_CONST}(); 
+0

偉大的作品 - 謝謝! – Jason

0
define('FIELD_TIME', 'field_time'); 
$entity->constant('FIELD_TIME')[LANGUAGE_NONE][0] = array(
    'value' => date_format($date), 
    'timezone' => 'UTC', 
    ); 

這樣應該工作,但是PHP 5.4

否則,你將需要一個更行:

define('FIELD_TIME', 'field_time'); 
$field_time = constant('FIELD_TIME'); 
$entity->$field_time[LANGUAGE_NONE][0] = array(
'value' => date_format($date), 
     'timezone' => 'UTC', 
     ); 

http://php.net/manual/en/migration54.new-features.php

Function array dereferencing has been added, e.g. foo()[0].


如果我的理解正確的,它應該用作:

class Entity { 
    public $field_time = null; 
} 
$entity = new Entity(); 
/** 
* Instead of: 
* $entity->field_time[LANGUAGE_NONE][0] = array('key' => 'val'); 
*/ 
define('FIELD_TIME', 'field_time'); 
$field_time = constant('FIELD_TIME'); 
// or $field_time = FIELD_TIME; 
$entity->$field_time[LANGUAGE_NONE][0] = array('key' => 'val'); 
0

您不能直接從方法的返回值訪問數組。

$entity->constant('FIELD_TIME')[LANGUAGE_NONE][0] 

是錯誤的,經由陣列存儲的常數()首先在另一個變量和訪問LANGUAGE_NONE返回值。

0

如果我明白你的好,你只是想使用常量來調用正確的數組的名稱?

define('FIELD_TIME', 'field_time'); 
$entity->{FIELD_TIME}[LANGUAGE_NONE][0] = array(
    'value' => date_format($date), 
    'timezone' => 'UTC', 
); 

這個工作對我很好,如果你有一個名爲「field_time」