Search code examples
phpclassconstructorscope

How to access data defined in a class constructor from the global scope?


I am having trouble receiving the values I am pushing into my cards array. I don't know if it is that I am not calling the right property or I am just not adding into the array correctly.

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

Solution

  • $cards is a variable local to __construct: once that function ends, that variable evaporates. Instead, you probably want to make cards a member of the class:

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

    Then you can use $this->cards inside the object, or $deck->cards outside.