0

I'm trying to declare a global array but when trying to retrieve it it returns NULL

GamesManager.php

namespace TMSE;

use PDO;


class GamesManager extends Main {

protected $DB;

public $cards = array();

public function __construct() {
    global $cards;
     $this->$cards = array('2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'T' => 10, 'J' => 10, 'Q' => 10, 'K' => 10, 'A' => 11);
     var_dump($cards);
}


public function pullCard() {
    global $cards;
    var_dump($cards);
}
}

Both var_dumps return NULL

0

2 Answers 2

1

You seem to be a little confused about variable scope. There's also an errant $ in $this->$cards. While this is valid syntax, it's not doing what you expect.

Consider the following to get an idea of what's going wrong with your code. See comments and output at the end for explanation.

<?php

$cards = [4, 5, 6]; // Global scope

class GamesManager
{
    public $cards = []; // Class scope
    
    public function __construct()
    {
        $this->cards = [1, 2, 3]; // This will set the class variable $cards to [1, 2, 3];
        
        var_dump($this->cards); // This will print the variable we've just set.
    }
    
    public function pullCard()
    {
        global $cards; // This refers to $cards defined at the top ([4, 5, 6]);
        
        var_dump($this->cards); // This refers to the class variable named $cards
        /*   
        array(3) {
          [0]=>
          int(1)
          [1]=>
          int(2)
          [2]=>
          int(3)
        }
        */
        
        var_dump($cards); // This refers to the $cards 'imported' by the global statement at the top of this method.
        /*
        array(3) {
          [0]=>
          int(4)
          [1]=>
          int(5)
          [2]=>
          int(6)
        }
        */
    }
}

$gm = new GamesManager;
$gm->pullCard();
/*
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
array(3) {
  [0]=>
  int(4)
  [1]=>
  int(5)
  [2]=>
  int(6)
}
*/
Sign up to request clarification or add additional context in comments.

Comments

0

In this case you don't need a 'global' keyword. Just access your class attributes using $this keyword.

class GamesManager extends Main {

    protected $DB;

    public $cards = array();

    public function __construct() {
        $this->cards = array('2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'T' => 10, 'J' => 10, 'Q' => 10, 'K' => 10, 'A' => 11);
        var_dump($this->cards);
    }


    public function pullCard() {
        var_dump($this->cards);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.