PHP-如何访问由数组创建的对象


PHP - How to access a object created by an array

我是OOP的新手,想创建一个简单的纸牌游戏。我得到了以下代码:

class card{
  private $suit;
  private $rank;
  public function __construct($suit, $rank){
      $this->suit = $suit;
      $this->rank = $rank;
  }
  public function test(){
      echo $this->suit.' '.$this->rank;
  }
}
class deck{
  private $suits = array('clubs',   'diamonds', 'hearts', 'spades');
  private $ranks = array(2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A');
  public function create_deck(){
     $cards = array();
     foreach($this->suits as $suit) {
        foreach ($this->ranks as $rank) {
           $cards[] = new card($suit, $rank);
        }
     }
     print_r($cards);
  } 
 }

比如说,我的班级卡有发牌的功能。我该如何处理一个心灵之王?它已经创建,但我不知道如何访问它。

发牌的函数可能应该在deck类中,而不是card类中。它可能类似于:

public function deal_card() {
    $suit = $this->suits[array_rand($this->suits, 1)];
    $rank = $this->ranks[array_rand($this->ranks, 1)];
    return new card($suit, $rank);
}

请注意,它没有发过哪些牌的记忆。deck类可能应该有一个private $cards属性,其中包含所有卡的数组(您可以在构造函数中填充它,使用类似于create_deck函数中的循环)。然后,当你发牌时,你可以将其从这个阵列中移除:

public function deal_card() {
    if (count($this->cards) > 0) {
        $index = array_rand($this->cards, 1); // pick a random card index
        $card = $this->cards[$index]; // get the card there
        array_splice($this->cards, $index, 1); // Remove it from the deck
        return $card;
    } else {
        // Deck is empty, nothing to deal
        return false;
    }
}

实例化如下对象:

$card = new card('hearts', 'K');