2017-09-13 23 views
-2

更新:下面是完整的控制器方法:PHP數組不會assing鍵值

protected $game = []; 

private function stageAction($type, $actions) 
{ 
    if (env('APP_DEBUG')) { 
     Log::info('STAGE ACTION started with $type= '.$type.' *********************'); 
    } 

    $message     = []; 
    $this->game['sys_msg']  = []; 
    $this->game['stage_action'] = []; 

    switch ($type) { 

     case 'attack_end': 
      $message['action'] = 'ignore'; 
      $message['message'] = '<b>'.active_player()['nickname'].'</b> ends their attack.'; 
      $this->game['sys_msg'] = $message; 
      break; 

     case ...... 
      break; 

     default: 
    } 

    // If it is an "ignored" message then send it now 
    if ($this->game['sys_msg']['action'] == 'ignore') { 
     $this->broadcastSysMsg(); 
    } 

    if (env('APP_DEBUG')) { 
     Log::info('SYS MSG - '.print_r($this->game['sys_msg'], true)); 
    } 

在我Laravel控制器我有這樣一個全局屬性:

protected $game = []; 

在一個方法,我給它加上這樣的一個鍵:

$this->game['sys_msg'] = []; 

然後,添加值,它是這樣的:

$message['action'] = 'ignore'; 
$message['message'] = 'My message is blah blah blah...'; 
$this->game['sys_msg'] = $message; 

代碼再往下我通過登錄其輸出這樣的檢查是:

Log::info('SYS MSG - '.print_r($this->game['sys_msg'], true)); 

但我得到這個:

[] 

我想分配一個對象數組到這個值。爲什麼這不起作用,但沒有失敗?

回答

2

的幾個問題,你有沒有iniaizlied $message,你剛開始在它的設定值。要麼初始化它,要麼更好,直接分配它,因爲這會更快。

$message = [ 
    'action' => 'ignore', 
    'message' => 'My message is blah blah blah...' 
]; 

你也可以走一步,直接分配給它的game成員:

$this->game['sys_msg'] = [ 
    'action' => 'ignore', 
    'message' => 'My message is blah blah blah...' 
]; 

至於你沒有看到更新後的值,也可能是由許多因素引起,請發表一個完整的代碼示例。

編輯:

看到你的代碼示例幾個建議後。

不要像你一樣使用數組,爲sys_msg創建一個類,這樣你就不會冒險打錯類型,例如aCtion使用了一個奇怪的錯誤。您還可以確保將其初始化爲已知狀態。例如:

class SysMsg 
{ 
    const ACTION_IGNORE = 0; 
    const ACTION_PROCESS = 1; 

    protected $action; 
    protected $message; 

    public function __construct($action = self::ACTION_IGNORE, $message = null) 
    { 
    $this->action = $action; 
    $this->message = $message; 
    } 

    public function getAction() { return $this->action; } 
    public function getMessage() { return $this->message; } 
} 

class SysMsg_AttackEnd extends SysMsg 
{ 
    protected $player; 

    public function __construct($player) 
    { 
    parent::__construct(SysMsg::ACTION_IGNORE, ""); 
    $this->player = $player; 
    } 

    public function getMessage() 
    { 
    return '<b>' . $this->player['nickname'] . '</b> ends their attack.'; 
    } 
} 


private function stageAction($type, $actions) 
{ 
    switch($type) 
    { 
    case 'attack_end': 
     $msg = new SysMsg_AttackEnd(active_player()); 
     break;   
    } 

    if (isset($msg) && $msg->getAction() == SysMsg::ACTION_IGNORE) 
    { 
    $this->game['sys_msg'] = $msg; 
    $this->broadcastSysMsg(); 
    } 
} 
2

我可以知道,這個代碼

$this->game['sys_msg'] = []; 

這是這行之前或之後?

$message['action'] = 'ignore'; 
$message['message'] = 'My message is blah blah blah...'; 
$this->game['sys_msg'] = $message;