Kenan
Kenan

Reputation: 114

PHP can't find the declaration of a referenced constant

I have a simple class in PHP with a constant. In the constructor I'd like to use this constant in a for loop, however both the IDE and PHP say:

Notice: Use of undefined constant DECK_SUITS - assumed 'DECK_SUITS' in /../Deck.php on line 18

Here's the code of my class:

class Deck
{

private $cards = [];
const DECK_SUITS = [Suit::Club, Suit::Diamond, Suit::Heart, Suit::Spade];
const DECK_RANKS = [Rank::Ace, Rank::Two, Rank::Three, Rank::Four, Rank::Five, Rank::Six, Rank::Seven, Rank::Eight, Rank::Nine,
    Rank::Ten, Rank::Jack, Rank::Queen, Rank::King];

public function __construct() {
    foreach(DECK_SUITS as $suit) {
        foreach(DECK_RANKS as $rank) {
            $card = new Card($suit, $rank);
            $this->cards[] = $card;
        }
    }
}

So this error is shown for both DECK_SUITS as well as DECK_RANKS in my foreach loop.

I can't find what's wrong with my code.

Upvotes: 2

Views: 65

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

That's because they're class constants not global constants (created using the define() function), and need to be referenced differently, identifying the class that they're defined in:

foreach(Deck::DECK_SUITS as $suit) {
    foreach(Deck::DECK_RANKS as $rank) {

or self::DECK_SUITS and self::DECK_RANKS from within the class where they're defined

Upvotes: 4

Related Questions