0

Why is the instance still dealing cards? Even though clearly, the $isDealer tag is defaulted to false, except for the dealer?

$cards = array('Ace','2','3','4','5','6','7','8','9','10','Jack','Queen','King');
$suits = array('Hearts','Diamonds','Spades','Clubs');

class Person {
public $isDealer = false;
public $luck = 15;

public function dealCards() {
    if ($isDealer) {

        global $cards;
        global $suits;

        for ($i = 0; $i < 5; $i++) {
            $pulledcard = rand(0,count($cards)-1);
            $pulledsuit = rand(0,count($suits)-1);
            echo $dealt = $cards[$pulledcard] .' of '. $suits[$pulledsuit] . '<br>';
        }
    }
    else {
        return 'You\'re not a dealer';
        }
    }
}

class Baller extends Person { public $luck = 50; }
class Dealer extends Person { public $isDealer = true; }

$dealer = new Dealer();
$theman = new Baller();
$random = new Person();

echo $theman->dealCards();       //this should return you're not a dealer but it deals cards instead

The last part should return a "You're not a dealer!" but instead, it deals cards. The same goes with the actual "Dealer".

4 Answers4

5

You want

if ($this->isDealer) {
Cfreak
  • 19,191
  • 6
  • 49
  • 60
1

$isDealer does not mean $this->isDealer. It means a new, implicitly-created variable.

Plus, you can't override member variables like that.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

When you write

if ($isDealer)

You are not checking the value for the variable that you expect. Your code is asking whether the variable $isDealer within the scope of the function dealCards() exists or is true/false. In order to check whether the member variable $isDealer for the class Person is true/false you must use $this->isDealer. This ensures that you are checking the member variable $isDealer within the cope of Person and not within the scope of the member function. So, you should get the behavior you expect if you use

if ($this->isDealer)
PhiloEpisteme
  • 857
  • 3
  • 8
  • 19
0

When you have this line:

class Dealer extends Person { public $isDealer = true; }

is it possible that public $isDealer = true; will overwrite the public $isDealer in class Person{}, having it that $isDealer will always be true? from another point of view, if this script is the only place where you use $isDealer, it might not be really necessary to define it as public?