Wednesday, 22 February 2012

Q: What is oops in php with example?


Object Oriented Programming  is a paradigm which is nowadays the most popular way to develop any application and most of the modern day language is based on this paradigm.
·  Class
·  Object
·  Polymorphism
·  Dynamic Binding...etc
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.
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.
<?php
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.<br />';
}

/*** define some public methods ***/

/*** a method to show the vehicle price ***/
public function showPrice(){
  echo 
'This vehicle costs '.$this->price.'.<br />';
}

/*** a method to show the number of doors ***/
public function numDoors(){
  echo 
'This vehicle has '.$this->num_doors.' doors.<br />';
}

/*** method to drive the vehicle ***/
public function drive(){
  echo 
'VRRROOOOOOM!!!';
}

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

No comments:

Post a Comment