In object oriented programming, a class
is a construct that defines a collection of properties and methods. You can think of it as a template. For example, the following PHP code declares a class named "Item" and instantiates two objects of that class — a book and a vinyl record:
class Item { public $itemType; /* e.g. this could be "Book" or "CD" */ public $price; public function printPrice() { echo "The price of this {$this->itemType} is {$this->price} dollars."; } } $catch22 = new Item(); $catch22->itemType = "Book"; $catch22->price = 25; $catch22->printPrice(); /* prints: The price of this Book is 25 dollars. */ $americanPrayer = new Item(); $americanPrayer->itemType = "Vinyl Record"; $americanPrayer->price = 22; $americanPrayer->printPrice(); /* prints: The price of this Vinyl Record is 22 dollars */
Note that in this example, $catch22 and $americanPrayer are 2 objects. Objects are instances of a class. They share the common structure that the class defines. This common structure consists of the properties ($itemType and $price in the above example) and methods (functions; printPrice() in the above example) of the class. However, the properties of different objects may be different.
In the above example, the price and item type are different for 2 objects of the same class. But both objects have a printPrice() method, a price property and an itemType property that can be used.
Comparison chart
Special Cases
In some programming languages, e.g. Python, everything is an object. This means functions, variables, instances of a class and even actual classes are treated as objects by the programming language.
Comments: Class vs Object