|
Posted by Marcin Dobrucki on 09/26/61 11:28
Jace Benson wrote:
> Ok I have read alot of things on zend.com, php.net and other sites went
> to the wikibooks to try to understand how to use a class. I have this
> project I want to do that I am sure would work great with a class. I
> just don't grasp the whole concept, and how to do it.
Think of a class as a container for data and methods (functions)
which operate on that data. Here's something that might look like
classes for a deck of cards:
<?php
class Card {
var $suit;
var $value;
function Card() {
// somehow initializes a card
$this->suit = "spades";
$this->value = "10";
}
function display() {
echo "Hello, I am a " . $this->value . " of " . $this->suit ."\n";
}
}
class Deck {
var $cards = array(); // cards are stored here
var $size = 52; // 52 normal, 5
var $jokers = false; // boolean: if yes, adds 2 to deck size
function Deck() {
if ($this->jokers) {
$this->size += 2;
}
// eg. add "empty" cards to deck
for ($i=0; $i < $this->size; $i++) {
$this->cards[] =& new Card();
}
}
function shuffle() {
// some kind of function to reshuffle
$this->cards = array_reverse($this->cards);
}
function display() {
// displays the entire deck
foreach ($this->cards as $card) {
$card->display();
}
}
}
// Ok, so now that we have defined our classes, we can play some cards:
$d = new Deck();
$d->shuffle();
$d->display();
?>
And our script will output (in case above), 52 lines of: "Hello, I am
a 10 of spades".
/Marcin
Navigation:
[Reply to this message]
|