Solved

OO PHP: Class seems to vanish after calling a method in a parent class

Posted on 2004-09-21
11
208 Views
Last Modified: 2012-05-05
Hello,

I have this problem I just can find a solution for. I made a couple of card-game classes, and everything works fine until I attempt to call the method returnCardToDeck() in the class Game, from the class Hand. The way I did it is, as you can see below, by using parent::returnCardToDeck($oldcard) twice, working my way up from Hand->Player->Game and from there going into Deck.

The weird thing is that when I reach Game, and attempt to call a method in Deck (near ((((MARK)))) ), the class Deck seems to have vanished from Game! I keep getting an error that I attempt to call a function of a non-object...
Near ((((MARK2)))) Deck is still in existance.

Now i have 2 questions:

-What am I doing wrong here?
-Is there a faster way to call the function returnCardToDeck() in the class Deck, while in the class Hand? Why doesnt something like this work: parent->parent->deck->returnCardToDeck() ?

Here is some of the classes code (i left out parts that had nothing to do with the problem):

class Game
{
      var $deck;
      var $amountofplayers;
      var $players;

      function Game($amountofplayers)
      {
            $this->amountofplayers = $amountofplayers;
            $this->players = array();
            $this->deck = new Deck();
            for ($x=1;$x<=$amountofplayers;$x++)
            {
                  $pid = "P".$x;
                  array_push($this->players, new Player($pid));
            }
      }

      function swap1card($player_id,$card_id)
      {
            foreach ($this->players as $player)
            {
                  if ($player->getId() == $player_id)
                  {
                        $card = $this->deck->drawCards(1);
((((MARK2))))
                        print_r($this->deck);
                        $player->swapCard($card_id,$card[1]);
                  }
            }
      }

      function returnCardToDeck($oldcard)
      {
            // ((((MARK))))
            //$this->deck seems to no longer be an object here!!!! Its just empty!
            $this->deck->returnCardToDeck($oldcard);
      }
}

class Deck extends Game
{
      var $cards;
      function Deck()
      {
            // ***
            //Code that is generating cards is here....
            // ***
      }

      // Returns $card (which should be a valid card object) to the back of the deck
      function returnCardToDeck($oldcard)
      {
            array_push($this->cards, $oldcard);
      }
}

class Player extends Game
{
      var $player_id;
      var $hand;
      
      function Player($player_id)
      {
            $this->player_id = $player_id;
            $this->hand = new Hand;
      }
      
      // Draw 1 card from the deck and add it on top of the pile of cards player is holidng
      function getCard($card)
      {
            $this->hand->addCard($card);
      }
      
      function swapCard($card_id, $card)
      {
            $this->hand->swapCard($card_id, $card);
      }
      
      function returnCardToDeck($oldcard)
      {
            parent::returnCardToDeck($oldcard);
      }
            
}

class Hand extends Player
{
      var $cards;
      var $colors;
      var $values;
      var $vector;
      var $c_flush;
      
      function Hand()
      {
            $this->cards = array();
      }
      
      function addCard($card)
      {
            array_push($this->cards, $card);
      }
      
      function returnCardToDeck($oldcard)
      {
            parent::returnCardToDeck($oldcard);
      }
      
      function swapCard($card_id, $newcard)
      {
            $card_id = $card_id - 1;
            //Return old card to deck
            $this->returnCardToDeck($this->cards[$card_id]);
            //Replace part from $this->cards, starting from position $card_id, length 1, by $newcard
            array_splice($this->cards, ($card_id-0), 1, array($newcard));
      }
}

Thanks for considering. If required, I can post the entire class code here.
0
Comment
Question by:Ildefonse
  • 6
  • 4
11 Comments
 
LVL 48

Expert Comment

by:hernst42
ID: 12120143
Yes that correct that that error occurs.
Hand extends Player extends Game
but you never call the constructor of the parent class
e.g:
     function Hand()
     {
          $this->cards = array();
     }

should be:
     function Hand()
     {
          $this->Player();
          $this->cards = array();
     }
same should apply to Player. So the Deck gets initialized. But I think what you wanted to do and what you programmed is wrong.

Why need the class Hand to be extended from the class Player? I think class Player uses a Class Hand and the Hand belongs to a player. The same applies to Player and Game. So you should recheck your design.
So in Hand the function returnCardToDeck($oldcard) should do this:
$this->Player->returnCardToDeck($oldcard);
and in Player the function returnCardToDeck($oldcard) should do this:
$this->Game->returnCardToDeck($oldcard);

Hope this gets you on the right way.
0
 
LVL 4

Expert Comment

by:aratani
ID: 12123328
Can you post your whole class code so that I can look at it?

Thanks

AJ
0
 
LVL 1

Author Comment

by:Ildefonse
ID: 12125123
Okay i have tried this:

So in Hand the function returnCardToDeck($oldcard) should do this:
$this->Player->returnCardToDeck($oldcard);
and in Player the function returnCardToDeck($oldcard) should do this:
$this->Game->returnCardToDeck($oldcard);

But that does not work. It generates the error "Call to a member function foo() on a non-object". When I am located inside a method of Hand, the code does not recognize $this->Player as an object apparently, regardless of whether I extend Hand from Player or not.

I do have managed to let my function work, but I did this in a different way:

In class Hand the old card is returned by means of a funtion return:

function swapCard($card_id, $newcard)
      {
            $card_id = $card_id - 1;
            //Return old card to deck
            $oldcard = $this->cards[$card_id];
            //Replace part from $this->cards, starting from position $card_id, length 1, by $newcard
            array_splice($this->cards, ($card_id-0), 1, array($newcard));
            return $oldcard;
      }

And after using this function I inject the $oldcard back into the pile using a method from the Game->Deck classes. Here is my entire class code:

//***
//* Class Game
//****************************************************************************************************
class Game
{
      var $deck;
      var $amountofplayers;
      var $players;

      function Game($amountofplayers)
      {
            $this->amountofplayers = $amountofplayers;
            $this->players = array();
            $this->deck = new Deck();
            for ($x=1;$x<=$amountofplayers;$x++)
            {
                  $pid = "P".$x;
                  array_push($this->players, new Player($pid));
            }
      }

      function makeNewDeck()
      {
            $this->deck = new Deck();
      }
      
      function getDeck()
      {
            return $this->deck;
      }
      
      function getAmountOfPlayers()
      {
            return $this->amountofplayers;
      }
      
      function getPlayers()
      {
            return $this->players;
      }
      
      function deal5Cards()
      {
            //Make a loop 5 times and each time deal a card to each player
            for($x=1;$x<=5;$x++)
            {
                  foreach ($this->players as $player)
                  {
                        $card = $this->deck->drawCards(1);
                        $player->getCard($card[1]);
                  }
            }
      }
      
      function swap1card($player_id,$card_id)
      {
            foreach ($this->players as $player)
            {
                  if ($player->getId() == $player_id)
                  {
                        $card = $this->deck->drawCards(1);
                        return $player->hand->swapCard($card_id,$card[1]);
                  }
            }
      }

      function returnCardToDeck($oldcard)
      {
            $this->deck->returnCardToDeck($oldcard);
      }
      
}

//***
//* Class Deck
//****************************************************************************************************
class Deck
{
      var $cards;
      
      function Deck()
      {
            // Define $cards as an array
            $this->cards = array();
            
            // Upon creation of a new cardpack add 52 cards with values 2 to 14 and colors H/C/D/S to $cards.
            for ($color_count=1;$color_count<=4;$color_count++)
            {
                  // First define the colors
                  switch ($color_count)
                  {
                        case 1:
                        $color = "H";
                        break;
                        
                        case 2:
                        $color = "C";
                        break;
                        
                        case 3:
                        $color = "D";
                        break;
                        
                        case 4:
                        $color = "S";
                        break;
                  }
                  
                  // Now define the values
                  for ($value=2;$value<=14;$value++)
                  {
                        // Make a new card
                        array_push($this->cards, new Card($value, $color));
                  }
                  
            }
            
            $this->shuffleDeck();
      }
      
      //Shuffle the deck
      function shuffleDeck()
      {
            shuffle($this->cards);
      }
      
      //Get the amount of cards in this deck
      function getAmountOfCards()
      {
            return count($this->cards);
      }
      
       // Returns an array with all cards in deck
      function getCards()
      {
                   return $this->cards;
      }
      
      // Draw the card at the beginning of the pile
      function drawCards($amount)
      {
            $cardsdrawn = array();
            for($x=1;$x<=$amount;$x++)
            {
                  $cardsdrawn[$x] = array_shift($this->cards);
            }
            return $cardsdrawn;
      }
      
      // Returns $card (which should be a valid card object) to the back of the deck
      function returnCardToDeck($oldcard)
      {
            array_push($this->cards, $oldcard);
      }
      
}
//***
//* Class Card
//****************************************************************************************************
class Card
{
      var $value;
      var $color;
      
      function Card($value,$color)
      {
            $this->value = $value;
            $this->color = $color;
      }

      function getValue()
      {
                  return $this->value;
      }

      function getColor()
      {
            return $this->color;
      }
      
}
//***
//* Class Player
//****************************************************************************************************
class Player
{
      var $player_id;
      var $hand;
      
      function Player($player_id)
      {
            $this->player_id = $player_id;
            $this->hand = new Hand;
      }
      
      // Draw 1 card from the deck and add it on top of the pile of cards player is holidng
      function getCard($card)
      {
            $this->hand->addCard($card);
      }
      
      function getId()
      {
            return $this->player_id;
      }

      function getHand()
      {
            return $this->hand->getCards();
      }
            
}
//***
//* Class Hand
//****************************************************************************************************
class Hand
{
      var $cards;
      
      function Hand()
      {
            $this->cards = array();
      }
      
      function addCard($card)
      {
            array_push($this->cards, $card);
      }
      
      function swapCard($card_id, $newcard)
      {
            $card_id = $card_id - 1;
            //Return old card to deck
            $oldcard = $this->cards[$card_id];

            //Replace part from $this->cards, starting from position $card_id, length 1, by $newcard
            array_splice($this->cards, ($card_id-0), 1, array($newcard));

            return $oldcard;
      }
      
      function getCards()
      {
            return $this->cards;
      }
}

===============================================================================
I have one additional question; is there a faster way than..

foreach ($this->players as $player)
            {
                  if ($player->getId() == $player_id)
                  {
                        $card = $this->deck->drawCards(1);
                        return $player->hand->swapCard($card_id,$card[1]);
                  }
            }

..to pick the proper $player from $this->players based on the player_id?

Thanks.
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 48

Expert Comment

by:hernst42
ID: 12125495
Index the array you are creating with the pid.
function Game($amountofplayers)
{
          $this->amountofplayers = $amountofplayers;
          $this->players = array();
          $this->deck = new Deck();
          for ($x=1;$x<=$amountofplayers;$x++)
          {
               $pid = "P".$x;
               $p = new Player($pid);
               $this->players[$p->getID()] = &$p;
          }
}

Then you can access a specific player by
$this->player[$player_id]->hand ...
0
 
LVL 1

Author Comment

by:Ildefonse
ID: 12126987
Thanks hernst42! That's indeed a simple but elegant solution. I'll split some points up for you :)
0
 
LVL 1

Author Comment

by:Ildefonse
ID: 12127019
On a side note, why would $p need to be assigned by reference here?
0
 
LVL 48

Expert Comment

by:hernst42
ID: 12127128
If you are using PHP4 = makes a copy of objects. So it can happen that you modify a copy of an object instead of the real object. If you loop with foreach over objects the result may not the one you are expecting. Should also work if you don't use the as you are not referencing other objects in Player (like the game-object)
0
 
LVL 1

Author Comment

by:Ildefonse
ID: 12127153
I am using php5, and adding the & messed up the code (dealing all cards 25 times).

Does = still make copies of objects in php5?
0
 
LVL 1

Author Comment

by:Ildefonse
ID: 12127199
I changed the code to:

            for ($x=1;$x<=$amountofplayers;$x++)
            {
                  $pid = "P".$x;
                  $this->players[$pid] = new Player($pid);
            }

removing $p from the code.
0
 
LVL 48

Accepted Solution

by:
hernst42 earned 300 total points
ID: 12127257
no with php5 you don't need that. There objects are passed by reference and not coppied anymore. Will make a lot things more easy when working with objects.
0
 
LVL 1

Author Comment

by:Ildefonse
ID: 12127733
great thanks :)
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

789 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question