2016-11-07 108 views
1

我無法接收我推入卡陣列的值。我不知道是否我沒有調用正確的屬性,或者我只是沒有正確添加到數組中。在PHP中將數值推入陣列

<?php 

class Deck{ 

    public function __construct(){ 
     $values =array('2','3','4','5','6','7','8','9','10','J','Q','K','A'); 
     $suits =array('Diamond','Club','Heart','Spade'); 
     $cards = array(); 
     foreach ($suits as $suit) { 
      foreach($values as $value){ 
       $cards[] = "$value of $suit's"; 
      } 
     } 
    } 
} 

$deck = new Deck(); 
var_dump($deck); 
+0

您在$ cards [] =「$ value of $ suit's」中有單引號; ..是一個錯字? – scaisEdge

+0

$ cards [] = $ value。「of」。$ suits; – Mart

+0

'$ deck'是你的對象。在你的構造函數中,你有一個局部變量'$ cards'來存放你創建的數組。只要在構造函數中使用'print_r($ cards)'! – Rizier123

回答

3

$cards是一個局部變量__construct:一旦函數結束時,該變量蒸發。相反,你可能想使cards類的成員:

class Deck { 
    public $cards = []; 

    public function __construct() { 
     $values =array('2','3','4','5','6','7','8','9','10','J','Q','K','A'); 
     $suits =array('Diamond','Club','Heart','Spade'); 
     $cards = array(); 
     foreach ($suits as $suit) { 
      foreach($values as $value){ 
       $this->cards[] = "$value of $suit's"; 
      } 
     } 
    } 
} 

然後你可以使用$this->cards物體內部,或$deck->cards之外。

+0

然後做var_dump($ deck-> cards); ? – Mart

+0

@MartHaarman自然。 ;) – bishop

+0

哈哈只是說:P – Mart