Tuesday 31 July 2012

Introduction to classes of PHP


Object-oriented PHP
If you have used an object oriented language before, you know that the subject is complex. I will present object-oriented PHP in a very simplistic manner but enough that you can learn to use objects in your scripts in a matter of minutes. Like any object-oriented language, PHP involves using classes to define objects and then using object instances to perform a task. The main purpose of a class is to provide instructions that define the functionality of an object. The class “Fruit” will provide information on a fruit such as shape and color. Let’s look at the definition of a class called Fruit.
<?
class Fruit {
// these are the instance variables
var $shape;
var $color;
// this is the constructor
function Fruit($shape=NULL, $color=NULL) {
$this->color = $color;
}
// the remaining functions are member functions
// to set or retrieve the state of the object
//ACCESSOR MTHODS
function getColor() { return $this->color; }
function getShape() { return $this->shape; }
//MUTATOR METHODS
function setColor($color) { $this->color = $color; }
function setShape($shape) { $this->shape = $shape; }
//A PRINT UTILITY
function printVar () {
echo “. variables are: ($this->shape) and ($this ->color)”;
}
}
?>
The class Fruit has two instance variables ($shape and $color), a constructor (function Fruit()), accessor and mutator functions. The instance variables describe the properties of a Fruit object. The constructor is used to create new Fruit objects. Constructors of a class always have the same name as the class. Here in the Fruit class, the constructor can take two optional parameters to create a new Fruit. The parameters are optional because they are each given a default value (null in our case) in the definition of the constructor. The member functions either get or set the values of the instance variables. Here is an example of how to create and use Fruit objects:
<?
Click Here For More    Introduction to classes of PHP

0 comments:

Post a Comment