arrays - How do I return an object with array_shift() in PHP? -


i'm building classes working playing cards. have card class , deck class. want implement drawing card deck using array_shift() on array of card objects; array property of deck. here code classes, stored in file "cardlib.php":

<?php class card {  private $suit="";  private $face="";   function __construct($suit,$face){     $this->suit=$suit;     $this->face=$face;  }   public function getsuit(){     return $suit;  }   public function getface(){     return $face;  }   public function display(){     echo $this->suit.$this->face;  }  }   class deck {  private $suits=array("s","h","c","d");  private $faces=array("2","3","4","5",             "6","7","8","9","10",             "j","q","k","a");  private $stack=array();   function __construct(){     foreach ($this->suits $suit){         foreach ($this->faces $face){             $card = new card($suit,$face);             $stack[] = $card;         }     }   }   public function doshuffle(){     shuffle($this->stack);  }   public function draw(){     $card = array_shift($this->stack);     var_dump($card);     return $card;  }  }  ?> 

and here test code, in "index.php":

<?php include_once "cardlib.php"; $mydeck=new deck(); $mydeck->doshuffle(); $card=$mydeck->draw(); $card->display();  ?> 

the test code gives me following error message:

null fatal error: call member function display() on non-object in c:\wamp\www\cardgames\index.php on line 6

it seems array_shift() isn't returning reference card object, or i'm not initializing $card variable array_shift() returns. how object want?

in constructor, store stack in local variable. use $this->stack store in member variable.

function __construct(){    foreach ($this->suits $suit){        foreach ($this->faces $face){            $card = new card($suit,$face);            $this->stack[] = $card;        }    } } 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -