Webeks.net - freelance programming
freelance programming - php, Joomla, Zend ...
Home :: Articles :: Programming :: PHP :: Class vs Object - the difference explained

Class vs Object - the difference explained

Written by Miha

Class

A class is a code template used to generate objects. It is some sort of a blueprint that describes the object.

In PHP a class name can be alphanumerical string that cannot begin with a number. Class code must be enclosed with braces and it consists of attributes and operations.

Example

  1. class Car {
  2.  
  3. //some variable
  4. private $owner;
  5.  
  6. //operation
  7. public function setOwner() {
  8. //something to do ...  
  9. }
  10.  
  11. }

Object

An object is data that is structured according to the template defined in a class. It is instance of a class.

Example

  1. $myCar = new Car();
  2. $obamasCar = new Car();
  3.  
  4. print $myCar; //outputs Object id #1
  5. print $obamasCar; //outputs Object id #2

In real world, you'll often find many individual objects all of the same kind. As an example, there may be thousands of other cars in existence, all of the same make and model even owned by the same person. Each car was built from the same blueprint. In object-oriented terms, we say that the car is an instance of the class of objects known as cars.


blog comments powered by Disqus