Definition of a Class



Definition of a Class

A class is user defined data type that contains attributes or data members; and methods which work on the data members. (You will learn more about data members and methods in following tutorials. This tutorial focuses only on learning how to create a Class in PHP5)
To create a class, you need to use the keyword class followed by the name of the class. The name of the class should be meaningful to exist within the system (See note on naming a class towards the end of the article). The body of the class is placed between two curly brackets within which you declare class data members/variables and class methods.

Following is a prototype of a PHP5 class structure
class <class-name> {
 
 <class body :- Data Members &amp; Methods>;
 
}
On the basis of the above prototype, look below an example of PHP5 class
Example of a Class:
class Customer {
 private $first_name, $last_name;
 
 public function setData($first_name, $last_name) {
  $this->first_name = $first_name;
  $this->last_name = $last_name;
 }
 
 public function printData() {
  echo $this->first_name . " : " . $this->last_name;
 }
}
In the above program, Customer is the name of the class and $first_name/$last_name are attributes or data members. setData() and printData() are methods of a class. We will discuss more about attributes and members in the upcoming articles on PHP5 OOPS Tutorials series.
Note:
You can read more about private, public and protected in this tutorial on Access Specifiers
Naming Conventions
Naming Convention for Class:
As a general Object Oriented Programming practice, it is better to name the class as the name of the real world entity rather than giving it a fictitious name. For example, to represent a customer in your OOAD model; you should name the class as Customer instead of Person or something else.
Naming Conventions for Methods:
The same rule applies for class methods. The name of the method should tell you what action or functionality it will perform. E.g. getData() tells you that it will accept some data as input and printData() tells you that it will printData(). So ask yourself what you would name a method which stores data in the database. If you said storeDataInDB() you were right.
Look at the manner in which the method storeDataInDB() has been named. The first character of the first word of the method is lower case i.e. ‘s‘tore. For rest of the words in the function viz Data/In/DB have been named as first character Uppercase and the remaining characters of the words as lower case i.e. ‘D’ata ‘I’n ‘D’B. Therefore it becomes storeDataInDB()
Naming Convention for Attributes:
Attributes of a class should be named on the basis of the data that they hold. You should always give meaningful names to your attributes. For attributes you should split the words with an underscore (_) i.e. $first_name, $last_name, etc.
/p>