| Object Oriented Programming |
| |
| Creating and Using Classes in PHP5 |
| |
| Defining a PHP Class |
| |
| Before an object can be instantiated we first need to define the class 'blueprint' for the object. Classes are defined using the class keyword followed by braces which will be used to enclose the body of the class: |
| |
<?php
class employee_details {
}
?>
|
| |
| We have now defined a class. The next step is add some functionality to the class. |
| |
| PHP Class Constructors and Destructors |
| |
| The next step in creating a class is to define what should happen when an object is first instantiated using the class, and also when that object is later destroyed. These actions are defined in the constructor and destructor methods of the class. |
| |
| The constructor and destructor are really just functions that get called when the object is created and destroyed and are defined in the class body using the function keyword. This needs to be prefixed with the public qualifier. |
| |
| This means the method is accessible to code outside of the object. The default names for the constructor and destructor are __construct and __destruct respectively. Both methods can take arguments to be used in initializing the object. These are declared in the same way arguments are defined in any function (see PHP Functions for details). |
| |
| We can now extend our employee_details class to include a constructor and destructor: |
| |
<?php
class employee_details{
public function __construct($emp_id,$emp_name,$addr)
{
echo "Constructor Called with the following values<br>";
echo "Employee ID = ".$emp_id."<br>E mployee Name = ".$emp_name."<br>Address = ".$addr;
}
public function __distruct(){}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> PHP Tutorial: Working with Classes </TITLE>
<META NAME="Generator" CONTENT="jNote-iT">
</HEAD>
<BODY>
<?php
$emp=new employee_details("EMP0012","Aman Singh","B-320, Sector 44, Rohni");
?>
</BODY>
</HTML>
|
| |
| When the example is loaded into a browser we should get the following output: |
| |
 |
| |
| Creating Members in a PHP Class |
| |
| Class members are essentially variables and methods embedded into the class. Members can be public or private and static or variable. |
| |
| Public members can be accessed from outside the object. Private members can only be accessed by methods contained in the class. This key to what is called data encapsulation. Object-oriented programming convention dictates that data should be encapsulated in the class and accessed and set only through the methods of the class (typically called getters and setters). |
| |
| Members declared as static are immutable, in that once defined they cannot be changed (much like constants). Members and functions are prefixed with public, private and static when declared in the class. The default is public non-static. |
| |
| We can now extend out employee_details class to add member variables to hold the account name and number passed into the constructor. True to the concept of data encapsulation we will be creating methods to access these values later, so will mark them as private. We will also add to our constructor to assign the passed arguments to our new members. |
| |
| When doing so we need to use the $this variable to tell PHP we are setting variables in the current class: |
| |
<?php
class employee_details{
private $emp_id;
private $emp_name;
private $addr;
public function __construct($emp_id,$emp_name,$addr)
{
$this->emp_id=$emp_id;
$this->emp_name=$emp_name;
$this->addr=$addr;
echo "Constructor Called with following values:";
echo "<br>Employee ID : ".$this->emp_id;
echo "<br>Employee Name : ".$this->emp_name;
echo "<br>Address : ".$this->addr;
}
public function __distruct(){}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> PHP Tutorials: Working with Classes </TITLE>
<META NAME="Generator" CONTENT="jNote-iT">
</HEAD>
<BODY>
<?php
$emp=new employee_details("EMP0012", "Aman Singh","B-320, Sector 44, Rohni");
?>
</BODY>
</HTML>
|
| |
| The next task is to define methods that will give us access to our data. |
| |
| Defining and Calling Methods |
| |
| We define our own methods in much the same way as we declared the constructor and destructor methods with exception that we get to choose the names. |
| |
| We declare methods inside PHP classes in the fashion we declare methods outside, the only difference being that, we may specify an access specifier like public, private etc.
To demonstrate this we will add to our class to provide methods to get and set the Employee id, name and address: |
| |
| Source code for Employee.class.php |
| |
<?php
class employee_details{
private $emp_id;
private $emp_name;
private $addr;
function __construct($emp_id,$emp_name,$addr)
{
$this->emp_id=$emp_id;
$this->emp_name=$emp_name;
$this->addr=$addr;
}
//Setter Methods of employee details class
public function setEmpID($emp_id)
{
$this->emp_id=$emp_id;
}
public function setEmpName($emp_name)
{
$this->emp_name=$emp_name;
}
public function setEmpAddr($addr)
{
$this->addr=$addr;
}
//getter Methods of employee details class
public function getEmpID()
{
return $this->emp_id;
}
public function getEmpName()
{
return $this->emp_name;
}
public function getEmpAddr()
{
return $this->addr;
}
public function display_details()
{
echo "<br>Employee ID : ".$this->emp_id;
echo "<br>Employee Name : ".$this->emp_name;
echo "<br>Address : ".$this->addr;
}
}
?>
|
| |
| Save the above script as employee.class.php |
| |
| Now that we have defined our getter and setter method to get and set the employee values we can call the methods. This is done by specifying the name of the object on which the methods are being called. This is followed by '->', and then the name of the method we are calling (including the parentheses containing any arguments required): |
| |
$emp2=new employee_details("","","");
//Using setter metter to set the employee details
$emp2->setEmpID("EMP0032");
$emp2->setEmpName("Neelam Rai");
$emp2->setEmpAddr("C-216/2, Barakhamba Road, New Delhi");
|
| |
| Complete Source code of employee_class.php |
| |
<?php
require ("employee.class.php");
?>
<HTML>
<HEAD>
<TITLE> PHP Tutorials: Working with Classes </TITLE>
<META NAME="Generator" CONTENT="jNote-iT">
</HEAD>
<BODY>
<?php
$emp1=new employee_details("EMP0012", "Aman Singh","B-320, Sector 44, Rohni");
$emp2=new employee_details("","","");
//Using setter metter to set the employee details
$emp2->setEmpID("EMP0032");
$emp2->setEmpName("Neelam Rai");
$emp2->setEmpAddr("C-216/2, Barakhamba Road, New Delhi");
#Displaying Details of Employee 1
echo "<h3>Details of Employee 1</h3>";
$emp1->display_details();
#Displaying details of Employee 2
echo "<h3>Details of Employee 1</h3>";
$emp2->display_details();
echo "<br> <b> Name of Employee 2 is : ".$emp2->getEmpName()."</b>";
?>
</BODY>
</HTML>
|
| |
| The above example sets the account name and number when instantiating the object. It then the getEmpName (to verify the change), thereby producing the following output: |
| |
 |
| |
| Getting Information about a PHP Object |
| |
| There are number of ways to find out information about classes.
An array of classes to which your script has access can be obtained using the get_declared_classes() function. The class_exists() function can be passed the name of a class to find out if such a class exists. A list of methods in a class can be obtained by passing the class name through to the get_class_methods() function. |
| |
| It is also possible to find out if a class has a parent class using the get_parent_class() function which will either return the name of the parent class, or an empty string if no parent exists.
The method_exists() function, when passed an object pointer and method name as arguments, will return a true or false value indicating the existence of the method. |
| |
| Inheritance and sub classing in PHP5 |
| |
| Once a class has been defined it is possible to create a new class derived from it that extends the functionality of the original class. The parent class is called the superclass and the child the subclass. The whole process is referred to as 'subclassing. |
| |
| A subclass of a class can be defined using the extends keyword when declaring the subclass.
For example we might choose to create a subclass of our employee_details class called tech_employee which defines an interest bearing type of employee: |
| |
<?php
require ("employee.class.php");
class tech_employee extends employee_details
{
private $dept;//Variable to store Department of the Employee
private $team_id;//Variable to store Team ID of the employee
private $prj_name;//Variable to store name of the Project employee is currently working on
private $prj_role; // Variable t o store Role of the employee in the project
//other tech_employee specific processing logic, methods etc
}
|
| |
| The important point to note here is that tech_employee inherits all the members and methods of employee_details and adds a new member(s) (such as team id[$team_id], project name[$prj_name], etc.). |
| |
| We can extend the class further by adding a new method to return other tech employee specific details: |
| |
| Source code of tech_employee.class.php |
| |
<?php
require ("employee.class.php");
class tech_employee extends employee_details
{
private $dept;//Variable to store Department of the Employee
private $team_id;//Variable to store Team ID of the employee
private $prj_name; // Variable to store name o f the Project employee is currently working on
private $prj_role; // Variable to s tore Role of the employee in the project
public function __construct($emp_id, $e mp_name,$addr,$dept,$team_id,$prj_name,$prj_role){
echo "Calling Parent Constructor";
parent::__construct($emp_id,$emp_name,$addr);
//Calling Parent Class Constructor with required Parameter
$this->dept=$dept;
$this->team_id=$team_id;
$this->prj_name=$prj_name;
$this->prj_role=$prj_role;
}
public function setDept($dept){
$this->dept=$dept;
}
public function setTeam_id($team_id){
$this->team_id=$team_id;
}
public function setPrjName($prj_name){
$this->prj_name=$prj_name;
}
public function PrjRole($prj_role){
$this->prj_role=$prj_role;
}
function getDept(){
return $this->dept;
}
function getTeamId(){
return $this->team_id;
}
function getPrjName(){
return $this->prj_name;
}
function getPrjRole(){
return $this->prj_role;
}
public function display_details(){
parent::display_details(); //calling parent's display method
#echo "<pre>";
echo "<br>Employee Department: <b>".$this->dept."</b>";
echo "<br>Team ID : <b>".$this->team_id."</b>";
echo "<br>Current Project : <b>".$this->prj_name."</b>";
echo "<br>Role in th e Current Project:<b>".$this->prj_role."</b>";
}
}
?>
|
| |
| In PHP parent keyword along with :: (scope resolution) operator is used to access parent class methods and properties. |
| |
| Source code of extended_employee.php |
| |
<?php
require ("tech_employee.class.php");
?>
<HTML>
<HEAD>
<TITLE> PHP Tutorials: Working with Classes </TITLE>
<META NAME="Generator" CONTENT="jNote-iT">
</HEAD>
<BODY>
<?php
$emp3=new tech_employee("TECH0031","Ravish Kumar","D-410, S ector 19, Noida","TECH-PHP","PHP03","EBIZ EDUCATION","PHP Developer");
echo "<h3>Details of Employee 1[TECH EMPLOYEE]</h3>";
echo "<pre>";
$emp3->display_details();
echo "</pre>";
?>
</BODY>
</HTML>
|
| |
| When this page is executed it produces the following output: |
| |
 |
| |
Assignment
1. Create a PHP class Simple_class and implement "Hello World!" using hello function in Simple_class
2. In the above Class create another function helloTo, which accepts an argument e.g. name and display "Hello :)".name.
3. Create a class Simple_calculator and implement Add & Subtract operation using member functions. Both functions should accept two arguments and return the result.
4. Create a class Adv_calculator which extends the Simple_calculator and contain three member function multi(), modulo() & division() besides the parent class methods. Call all 5 functions using object of Adv_calculaor.
5. Write a PHP Script to print a list of classes the script has access of.
6. Write PHP Script to check whether a method exists or not. |
| |
| |
|
| |
| |