Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I return an object with array_shift() in PHP?
    primarykey
    data
    text
    <p>I'm building some classes for working with playing cards. I have a Card class and a Deck class. I want to implement drawing a card from the deck by using array_shift() on an array of Card objects; this array is a property of Deck. Here is the code for the classes, which is stored in the file "cardlib.php":</p> <pre><code>&lt;?php class Card { private $suit=""; private $face=""; function __construct($suit,$face){ $this-&gt;suit=$suit; $this-&gt;face=$face; } public function getSuit(){ return $suit; } public function getFace(){ return $face; } public function display(){ echo $this-&gt;suit.$this-&gt;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-&gt;suits as $suit){ foreach ($this-&gt;faces as $face){ $card = new Card($suit,$face); $stack[] = $card; } } } public function doShuffle(){ shuffle($this-&gt;stack); } public function draw(){ $card = array_shift($this-&gt;stack); var_dump($card); return $card; } } ?&gt; </code></pre> <p>And here is the test code, in "index.php":</p> <pre><code>&lt;?php include_once "cardlib.php"; $myDeck=new Deck(); $myDeck-&gt;doshuffle(); $card=$myDeck-&gt;draw(); $card-&gt;display(); ?&gt; </code></pre> <p>The test code gives me the following error message:</p> <p>NULL Fatal error: Call to a member function display() on a non-object in C:\wamp\www\cardgames\index.php on line 6</p> <p>It seems that array_shift() isn't returning the reference to the card object, or I'm not properly initializing the $card variable with what array_shift() returns. How do I get the object that I want?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload