简体   繁体   中英

PHP - How to access a object created by an array

I'm quite new to using OOP and wanted to create a simple cardgame. I got the following code:

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);
  } 
 }

Say, for example that my class card had a function for dealing a card. How do I deal a king of hearts? which is already created but I don't know how to access it.

The function for dealing a card should probably be in the deck class, not the card class. It would be something like:

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);
}

Note that this has no memory of which cards were dealt. The deck class should probably have a private $cards property containing an array of all the cards (you can fill it in in the contructor, using a loop like in your create_deck function). Then when you deal a card, you can remove it from this array:

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM