Login |  Register 
Secure your virtual life!
This has got to be one of the most frequently updated PHP sites, keep up the good work...
Max
 

Classes and object orientation

Classes are used to define a real world thing, such as a person or a book. Once the class of thing has been defined then it can be instantiated.

An example class is below.

class Book
{
 private $title;
 private $author;
 private $isbn;
 private $reserved;

 public function Reserve()
 {
  $this->reserved = true;
 }
}

As you can see the the class is defined by using the class keyword followed by the name of the class which can be any non-reserved word in PHP. The variables and the function are all defined with the visibility modifier.

You will notice that the pseduo variable $this is used in the class. This variable allows functions and variables to be called from inside a class.

A class can be instantiated and called as shown below using the new

//Creates a instance of a class
$book = new Book();
//Calls the reserve function of the book object.
$book->Reserve();

Classes can also contain static functions. A static function doesn't require the class to be instantiated as a normal object method does. However a static method can't use any of the objects non-static variables.

class Book
{
 private $title;
 private $author;
 private $isbn;
 private $reserved;
 private static $bookTypes = array('Reference', 'Fiction');

 public function Reserve()
 {
  $this->reserved = true;
 }

 public static function GetBookType($index)
 {
  return self::$bookTypes[$index];
 }
}

As you can see above the static function can use static class variables such as $bookTypes. A static variable or function can be accessed either via the self keyword or the class name inside the class and just the class name from outside it, as shown below.

//This prints Reference
echo Book::GetBookType(1);

A default value for a class variable must be a constant expression, so no concatanation or creating new classes!


No comments have been provided.
security image
Written by Dominic Skinner
Last Updated: 2009-05-21 08:17:33