wow classes are big stuff !
Well, using classes is not better than just using functions, in itself. But actually sometimes you'd better choose to make OOP (Object Oriented Programming). This kind of programmation includes the use of classes.
Mainly, classes are a kind of object pattern, you define it once and you can create as many occurences as you want, those occurences are called instances.
For example, you can create a class that will represent an animal this way:
class Animal
{
//ATTRIBUTES :
var $name;
var $years;
var $species;
//constructor :
function Animal($localName,$localYears,$localSpecies)
{
$this->name=$localName;
$this->years=$localYears;
$this->species=$localSpecies;
}
//METHODS :
function getYears()
{
return $this->years;
}
function setYears($loaclYears)
{
$this->years=$localYears;
}
}
$myCat=new Animal("Fluffy",30,"cat");
$myDog=new Animal("Doggy",5,"dog");
In this basic example we've created a class containing 3 attributes (i.e. 3 properties of each instance) and 2 methods (i.e. 2 functions that have access to all of the instance' attributes).
After having defined the class, we've created 2 instances of it, with differnet properties. You can see that the constructor is a special method that is always called first when you instantiate a class (with the "new" keyword).
The main advantages of using classes are :
- modularity, you can easily re-use a class you defined months ago for another program.
- inheritance (also called derivation), that is to say you can write a class using another already existing. For example :
// We've already defined class Animal...
class Dog extends Animal
{
//constructor
function Dog($localName,$localYears)
{
Animal::Animal($localName,$localYears,"dog");
}
}
$myOtherDog=new Dog("Doggy Jr.",1);
So classes are a pretty useful tool...
You can find some cool tutorials on the web, should be helpful...