You are here: Re: Classes, don't follow. « PHP Programming Language « IT news, forums, messages
Re: Classes, don't follow.

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]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация