Php5 Tutorial – How to Compile Php5 Class

May 30, 2012, by admin

Class Definition

php5A class is user defined data type that includes features or data members; and techniques which work on the data members. (You will learn more about data members and techniques in following tutorials. This tutorial focuses only on learning how to Compile Class in PHP5)

To Compile a class, you require to utilize 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 techniques.

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;

}

}

 Naming Conventions

Naming Convention for Class:

As a common Object Oriented Programming practice, it is better to name the class as the name of the real world unit rather than giving it a fabricated 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 techniques. The name of the technique 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 technique storeDataInDB() has been named. The first character of the first word of the technique 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 features:

Features of a class should be named on the basis of the data that they hold. You should always give meaningful names to your aspects. For features you should split the words with an underscore (_) i.e. $first_name, $last_name, etc.