OOP: Class (Part 1)



Now, in the computer programming world, object-oriented programming (OOP) has rapidly taken hold as the programming methodology of choice for the enterprise. The basic concept is encapsulation - the grouping of data and code elements that shar common traits inside a container known as class.

Getting Started

A class contains the definition of data elements (or properties) and functions (or methods) that share some commont trait and can be encapsulated in a single structure. A class is declared using the class structure:

  <?
  // class keyword is followed by name of class: vehicle
  class vehicle
  {
    // Data property
   	var $type;
   	
    // a method, if same name as the class, 
//it as the class constructor. Automatically called 
//whenever class is instantiated
    // have paramater $type
   	function vehicle( $type )
   	{
     		$this->type = $type;
   	}
 
  }
 
  ?>
Instantiating a Class
  <?
  class vehicle
  {
   	var $type;
   	
   	function vehicle( $type )
   	{
     		$this->type = $type;
   	}
 
  }
 
  $obj = new vehicle( 'car' );
  echo $obj->type;
 
  ?>

The new operator causes a new instance of the vehicle class to be created and assigned to $obj. And method vehicle (as constructor) will be called automatically. We can pass parameters to its directly.



Series this article:
OOP: Class (Part 1)
OOP: Classes as Namespace (Part 2)
OOP: Implementing Inheritance ( Part 3 )


Tag: OOP Category: PHP Basic Post : November 17th 2007 Read: 1,908 Bookmark and Share

blog comments powered by Disqus