watkins1179 watkins1179 - 1 month ago 9
PHP Question

Trouble understanding the calling of global variables with in a class to a method within the class

I am having trouble with my numberOfDecks method. I try to call the array of cards that is created in my constructor, but the an error keeps coming up that I am passing an undefined variable ($cards). I thought since it is a global variable $cards would be able to be called to the numberOfDecks method.

<?php
/* creating a deck of cards class to be used in a blackJack game*/

class Deck{

public $cards = array();

//creates an instance of a deck of cards (works)

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

/*trying to add more decks to increase number of total cards
in my array (does not work)*/

public function numberOfDecks($number){

$this->cards = $cards;
$this->number= $number;
for($i = 0 ; $i < $number; $i++){
array_push($cards[],$i);
}
return $cards;

}
}



$deck = new Deck();//works as expected
$deck->numberOfDecks(3);//trouble
$shuffled = shuffle($deck->cards);//works as expected
var_dump($deck);

Answer

Your variable $cards is undefined because you don't declare it.

public function numberOfDecks($number){

$this->cards = $cards;

You probably meant to flip the assignment direction.

$cards = $this->cards;

Given your comment for adding decks to the object total deck, after flipping the assignment direction, try using array_merge

Here's a working fiddle.

<?php

class Deck{

  public  $cards = array();

  //creates an instance of a deck of cards (works)

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

    public function numberOfDecks($number){

        $cards = $this->cards;

        $this->number = $number;
        for($i = 0 ; $i < $number; $i++){
            $this->cards = array_merge($this->cards, $cards);
        }

    }
}



$deck = new Deck();//works as expected

// how many cards are intially constructed?
echo "count of cards in new deck: " . count($deck->cards) . "\n<br/>\n";

// add 3 more decks of cards
$deck->numberOfDecks(3);//trouble 
echo "count of cards after adding 3 decks: " . count($deck->cards);

// $shuffled = shuffle($deck->cards);//works as expected
// var_dump($deck);

Results in this output:

count of cards in new deck: 52
count of cards after adding 3 decks: 208