Monday, September 13, 2010

PHP 5 with OOPs

What is OOP

OOP was first invented for the purpose of physical modelling in the Simula-67.
Whilst there is no hard and fast definition of what Object Oriented Programming (OOP) is, we can define. So lets just use this loose definition for now and it is left to reader to make up their own minds about what a decent definition is. Object Oriented Programming (OOP) is a programming concept that treats functions and data as objects. OK, not the best definition but gives us an opening. The key word here is objects. As we progress through this tutorial we will see how data and functions can be represented as re-usable objects, thus cutting down on code and time.

What is an Object

Simply put, an oject is a bunch of variables and functions all lumped into a single entity. The object can then be called rather than calling the variables or functions themselves. Within an object there are methods and properties. The methods are functions that manipulate data withing the object. The properties are variables that hold information about the object.

What is a Class

A class is the blueprint for your object. The class contains the methods and properties, or the charactaristics of the object. It defines the object. Lets just start with some examples to see how it all pieces together. We will use a vehicle as our object. All vehicles share similar charactaristics, eg: number of doors, they are painted some color, they each have a price. All vehicles do similar things also, drive, turn left, turn right, stop etc. These can be described as functions, or in OOP parlance, methods. So, the class holds the definition, and the object holds the value. You declare class in PHP by using the class keyword.
class vehicle{/*** define public properties ***/

/*** the color of the vehicle ***/
public $color;
/*** the number of doors ***/public $num_doors;
/*** the price of the vehicle ***/public $price;
/*** the shape of the vehicle ***/public $shape;
/*** the brand of vehicle ***/public $brand;
/*** the constructor ***/public function __construct(){
  echo 
'About this Vehicle.';
}
/*** define some public methods ***/

/*** a method to show the vehicle price ***/
public function showPrice(){
  echo 
'This vehicle costs '.$this->price.'.';
}
/*** a method to show the number of doors ***/public function numDoors(){
  echo 
'This vehicle has '.$this->num_doors.' doors.';
}
/*** method to drive the vehicle ***/public function drive(){
  echo 
'VRRROOOOOOM!!!';
}

/*** end of class ***/?>

With this simple class definition we can now create one, or many, vehicle objects. Lets see how its done, then we will step through it all. To create a new object from the class definition we use the new keyword.

/*** create a new vehicle object ***/$vehicle = new vehicle;
/*** the brand of vehicle ***/$vehicle->brand 'Porsche';
/*** the shape of vehicle ***/$vehicle->shape 'Coupe';
/*** the color of the vehicle ***/$vehicle->color 'Red';
/*** number of doors ***/$vehicle->num_doors 2;
/*** cost of the vehicle ***/$vehicle->price 100000;
/*** call the showPrice method ***/$vehicle->showPrice();
/*** call the numDoors method ***/$vehicle->numDoors();
/*** drive the vehicle ***/$vehicle->drive();
?>
Using the combination of the two code boxes above, you should have something like..
About this vehicle.
This vehicle costs 100000.
This vehicle has 2 doors.
Lets step through the class definition first to see what its all about.
We began the class with the class keyword. This tells PHP that what follows is a class definition.

class vehicle{
?>
Next we declared some variables, or as they are known in the OOP world, properties.

/*** the color of the vehicle ***/public $color;
/*** the number of doors ***/public $num_doors;
/*** the price of the vehicle ***/public $price;
/*** the shape of the vehicle ***/public $shape;
/*** the brand of vehicle ***/public $brand;
?>
The properties are the individual charactaristics of the vehicle object. The public declares that this property may be accessed within the public scope. This means you may set it from within your code. Next in the class definition is this code..

/*** the constructor ***/public function __construct(){
  echo 
'About this vehicle.';
}
?>
The constructor method (function) is a special function that is executed every time a new object is created or "instantiated". If a class needs to do something before running some code, then this is the place to do it. It is often used to set properties within the class. You may pass a variable directly to the constructor from your code, but more of that later. Following the constructor is several methods (functions) that do things. These methods are also preceded by the public meaning they are available with the scope of your code.

/*** a method to show the vehicle price ***/public function showPrice(){
  echo 
'This vehicle costs '.$this->price.'.';
}
/*** a method to show the number of doors ***/public function numDoors(){
  echo 
'This vehicle has '.$this->num_doors.' doors.';
}
/*** method to drive the vehicle ***/public function drive(){
  echo 
'VRRROOOOOOM';
}
?>
As you see above, our methods are similar to normal PHP functions. However you may note the use of variables like $this->price and $this->num_doors. The keyword $this is used to refer to properties or methods within the class itself. The $this keyword is reserved in PHP, so it cannot be used as a variable or property name. Finally we finished our class definition with a closing }. I like to put a comment beside it so I dont delete it or get it confused with a function I am writing.
Following on from the class definition we see our userland code. This is the code we use to instantiate (create) a new instance, or new object, of our vehicle class. As mentioned earlier we do this with the use of the new keyword.

/*** create a new vehicle object ***/$vehicle = new vehicle;
?>
The code above creates a new object from our class definition called $vehicle. It is at this time that the constructor is called and any code within the constructor is executed. Once we have a new object we can then begin to assign values to the properties of that object as seen here.

/*** the brand of vehicle ***/$vehicle->brand 'Porsche';
/*** the shape of vehicle ***/$vehicle->shape 'Coupe';
/*** the color of the vehicle ***/$vehicle->color 'Red';
/*** number of doors ***/$vehicle->num_doors 2;
?>
With the properties set as above, it is now simple to use the object methods to manipulate the object by calling the methods. The methods are executed like this below.
/*** call the showPrice method ***/$vehicle->showPrice();
/*** call the numDoors method ***/$vehicle->numDoors();
/*** drive the vehicle ***/$vehicle->drive();?>
So, thats the step-by-step of your first class. You see how easy it would be now to create a new car object. Perhaps a Red Ferrari with 4 doors costing $250,000.00.

Commenting Code

In the previous sections you have seen comments for almost every line of code. This is a good practice, although some may find it excessive, as it may not be you who has to edit the code next time. OOP can get very abstracted and if you are not careful it is easy to lose site of your programmatical work flow. Most methods within a class will return a value, rather than echo a line of HTML code. A class method may also take one, or several, arguements. It is good practice to show what these arguements are and there types. An example follows below.
  /**
  * adds an array of numbers and returns the value
  *
  * @param array $numbers An array of numbers to add
  *
  * @access private
  *
  * @return int Returns sum of numbers
  *
  */
  
private function sum_of_numbers($numbers){
    
/*** return the sum of the $numbers array ***/
    
return array_sum($numbers);
  }
?>
The above function is rather simplistic, but shows well the commenting of code. The comments begin in a block of C type multiline comments and gives us a brief description of what it does, followed by the parameter it takes, in this case an array of numbers. It tells us that access to the function is private (more on this in the next section). Finally the comment block tells us that the return value is of type INT. We can also see within the function itself a single line comment just to show what is happening within the funtion itself. If you follow these practices you code will always be readable and easy to follow by yourself and others.

Inheritance (Extending a class)

Probably the greatest feature of the PHP OOP model is Inheritence. Inheritence is the ability of php to extend classes (child classes) that inherit the charactaristics of the parent class. The resulting object of an extend class has all the charactaristics of the parent class, plus whatever is in the new child, or extended class. In this instance we will extend the vehicle class and add a motorcyle. A motorcycle is still a vehicle and shares many of the same attributes such as price, drive etc. But a motorcycle has some unique features that a car does not.
Rather than type out the whole of the vehicle class definition again, we will save it in a file of its own called vehicle.class.php. It is important here to note the naming convention here as it will be important later in this tutorial. Lets see how it works.



/*** include the vehicle class definition ***/include('vehicle.class.php');

class 
motorcycle extends vehicle{
/*** the number of side cars ***/private $num_sidecars;

private 
$handlebars;
/**
*
* set the type of handlebars
*
* @access public
*
* @param string
*
* @return string
*
**/
public function setHandlebars($handlebarType){
  
$this->handlebars=$handlebarType;
}
/**
*
* Set number of side cars
*
* @access public
*
* @param int
*
* @return int
*
**/
public function setSidecar($numSidecars){
  
$this->numSidecars $numSidecars;
}

/**
*
* Show the numbers of sidecars
*
* @return string
*
**/
public function showSideCar(){
  echo 
'This motorcyle has '$this->numSidecars.' sidecar';
}

/*** end of class ***/


/*** our userland code ***/

/*** create a new vehicle object ***/
$vehicle = new motorcycle;
/*** the brand of vehicle ***/$vehicle->brand 'Harley Davidson';
/*** the shape of vehicle ***/$vehicle->shape 'Sportster';
/*** the color of the vehicle ***/$vehicle->color 'Black';
/*** number of doors ***/$vehicle->num_doors 0;
/*** cost of the vehicle ***/$vehicle->price 25000;
/*** type of handle bars ***/$vehicle->setHandlebars('Ape Hangers');
/*** set the sidecar ***/$vehicle->setSidecar(1);
/*** show the vehicle brand and type ***/echo $vehicle->brand.': '.$vehicle->shape.'';

/*** call the showPrice method ***/$vehicle->showPrice();
/*** show the sidecars ***/$vehicle->showSideCar();
/*** drive the vehicle ***/$vehicle->drive();
?>
You see in the motorcycle class that we have used the keyword extends to extend our vehicle class. We can then proceed to set vars in the both the parent class and the child class. The child class has inherited all the characaristics of the parent vehicle class.
If you run the above code with out including the parent class, you will get a Fatal Error like this:
Fatal error: Class 'vehicle' not found in /www/oop.php on line 3

You MUST include the class definition on *every page* when you store an object
This means when you use an object or wish to extend from it. you must include the class file. Either as code, or most commonly, with an include() statement.
 

No comments:

Post a Comment