10 OOP – I in PHP
Hiren Joshi
There are two main approaches for writing code to develop software system. The approaches are
1. Structure/Procedure Oriented and
2. Object Oriented Programming (OOP)
In procedure oriented programing the focus is on writing functions or procedures. These functions or procedures operate on data. For example, to develop library management system, procedure oriented approach focus on writing procedure like member registration, book issue, book return and fine calculation. While in Object Oriented Programming paradigm the focus is on object. An Object contains both data and functionality together. For Library Management System, the objects like member, book and librarian. There is an association between such objects like member return book. Software developed using OOP approach is considered easier to maintain, reuse and enhance. OOP approach facilitates developer to create modular, reusable and extendable code. So developer/programmer can write program by combining and modifying of existing code. That gives the facility to developer/programmer to change or replace modules without changing other parts of the code. Hence, OOP approach is capable to make rapid software application development.
To use procedure oriented approach or object oriented approach to develop system software is depend on personal preference. Neither approach is better than other. Though it is not recommended, you can use procedure and object oriented approach in a single PHP script.
Features of OOP
An object Oriented Programming language support following fundamental features.
- Encapsulation
- Inheritance
- Polymorphism
- Data Abstraction
Encapsulation means combing data and procedures as a single entity. Encapsulation facilitates data hiding. In OOP, you can code so that other users can change value of object‟s private properties using object‟s public method only. The code allows only access to class members, not class itself.
Inheritance encourages reusability. Once a class is created – known as parent class or base class – , it can be inherited by other class(es) – known as Child class(es). The child class will inherit all the properties and methods of parent class. Not only that, if required, child class can add new properties and methods or can be modified existing properties and/or methods.
Polymorphism is a Greek word. The meaning of poly in greek is much/more and morph means form/shape. That means polymorphism is an ability to use a single function in many ways different upon the usage. It supports to process object differently depending on their data type. For example, the function max can be defined in three different way which gives maximum intereger value, maximum floating point value and maximum length string. All the three functions have name is same “max” , but the signatures are different.
Data Abstraction hide implementation complexity though interface. It explains, what to do with hiding how it works. Data Abstraction means providing only essential information to the outside world and hiding background details. For example, a class in any OOP language provides different methods to the outside world but does not providing how it works to the outside world.
OOP Terminology
Class: Class is considered as programmer defined data type. A class is a blueprint or prototype of an object. Object cannot create without class.
Object: Object is an instance of a class. Object is created from the class. Many Objects created from a class.
Properties: Property is a data associated with object. Property is also known as Attribute or member variable.
Method: Method is a behavior associated with Object. Method is also known as behavior or member function.
Object can have attributes and methods.
Let us take an example to explain class and object. Cricketer is a class while Sachin, Saurav, Rahul are objects of cricketer class. Each cricketer objects has properties like their team name, they are wearing cricket playing clothes, and they are wearing cricket playing pair of shoes. The name, clothes and shoes are property or attribute of object. A cricketer can bat, bowl, field or wicket keeping. Batting, Bowling, Fielding, Wicket Keeping are methods or behavior of cricketer object. The attributes and methods associated with an object are collectively known as member of an object. Each object property has value. This value is known as state. For example: Ricky pointing is a cricketer object and the attribute team name value is Australia. The state of an object can be changed using method.
Syntax for creating a Class:
class <classname>
{
statement(s);
}
- Class is keyword.
- Classname is a name of class which you want to create
- For convention, classname begins with capital letter
Syntax for creating property
[ access modifier ] $PropertyName [ = initValue ];
- Access modifier can be either public or private or protected
- Public property is accessed outside the class
- Private or Protected property is not accessed outside the class
- A property can have an optional initialValue. The initialvalue must be a literal number or string or Boolean value , an array of literal number, string or Boolean value or the Null value.
- By default access modifier is Public. So if you omit the access modifier , the property is public. To make code more readable, it is recommended that access modifier should be place while defining property.
- Multiple properties can be defined in a single line. The comma (,) symbol is used to separate multiple property.
Few examples of properties are:
- private $empid;
- public $greetings = „‟;
- protected $total;
- private $eid, $efname, $elname, $edept;
Methods:
Syntax for creating a method
[ Access modifier ] function <functionName> ([parameterlist])
{
statement(s);
}
By default, methods access modifier is public. So you can omit the access modifier when you code method. However, to improve your code more readability, you should write access modifier when you write methods in a class.
Few examples of methods are:
function getsummary()
{
statement(s);
}
public function getDB()
{
statement(s);
}
public function getproduct($pid)
{
statement(s);
}
function simpleinterest($amt,$rate,$duration)
{
Statement(s);
}
Constructor:
Constructor or construction method is a special method. Constructor is executed automatically when a new object created from a class. Constructor is typically used to initialize property of the object.
Syntax for creating constructor
[ Access modifier ] function __construct ([parameterlist])
- Access modifier can be either public or private or protected
- Function is a keyword for function
- Construct (double underscore followed by keyword construct) is name of function. For creating construction you have to use the name “__construct “.
- In PHP a class may have only one constructor. As a result, if you want to pass variable length parameters, you can use the in-built PHP functions like func_num_args( ), func_get_args( ) and func_get_arg($arg). Another approach is that you can initially assign default value to each parameter, so you can pass variable numbers of parameter value. For example, you can write
- public function __construct($id = NULL, $name = NULL) ,
- So, you can pass zero, one or two arguments to the constructor.
- In case, a constructor method is not coded for the class, the class automatically provides default constructor. The default constructor . The default constructor does not include any parameters. Following code snippet shows default constructor
public function __construct( )
{
}
- Within a class, you can code a special variable named $this. $this stores a reference to the current object. As a result, $this is used to access the properties and methods of current object.
- To access an object‟s properties or methods, the object access operator is used. The object access operator is coded with -> (hyphen and greater than symbol). When you code object access operator, make sure that there is not any space between these two characters (hyphen and greater than).
Destructor:
Destructor or Destructor method is a special method. Destructor is executed automatically when an object is no longer available for use. Destructor is typically used when program execution reaches at the end of a function or script. Destructor can be also executed automatically when you code unset function to delete the reference to the object. The general use of destructor to release the resources such as database connections before the object is deleted.
Syntax for creating constructor
public function __destruct ( )
- Function is a keyword for function
- __destruct (double underscore followed by keyword destruct) is name of function. For creating construction you have to use the name “__destruct “.
- __destruct ( ) does not take any parameters.
Object:
- An object is an instance of a class
- Many objects can be created from a class.
- The process of creating an object from the class is known as instantiation
Syntax for creating an Object:
$objectName = new <ClassName> ([parameterlist]);
1.To access an object‟s properties or method, code object name followed by object access operator (->) and then code name of property/method.
2.If a function or method returns an object, then the function or method call can be used as a reference to the object and continue accessing the returned object‟s properties and methods. This is known as object chaining.
For example:
echo $obj->getcategory()->getName()
Let us understand the above theory by practical.
<?php
class Employee
{
private $eid, $ename; // properties of a class Employee
// Getter and setter to set properties of object
public function geteid() //get method to get employeeid
{
return $this->eid;
}
public function seteid($value) //set method to set employeeid
{
$this->eid = $value;
}
public function getename()
{
return $this->ename;
}
public function setename($value)
{
$this->ename = $value;
}
}
$obj = new Employee();
echo ‘<br> $obj is now : ‘;
print_r($obj);
- Here, we code a class named Employee.
- The class Employee has properties eid and ename. The access modifier of these properties is private. So they are not accessible outside the class.
- The class Employee has 4 methods geteid, seteid, getename, setename.
- Getid is used to get the eid while seteid is used to set the eid. In the same way, getname and setname is used for get and set ename respectively.
- The geteid method is used to read the property value and the seteid method is used to write the property value in above example. Generally get method is used to read the property value and set method is used to write the property value. So get method is read-only and set method is write-only. You can code only get or set method as per your coding requirement. The combination of get and set method is known as getter-setter.
- print_r function displays information about a varibale.
- Note that, $ sign is not coded between the object access operator(->) and property name when used with object reference ($this in above example).
The output of the above code is:
$obj is now : Employee Object ( [eid:Employee:private] => [ename:Employee:private] => )
Now let us code to seteid and ename , then the code will be
echo ‘<br>’;
$obj->seteid(101);
echo ‘<br> $obj is after setid is: <br> ‘;
print_r($obj); $obj->setename(‘Vipul’);
echo ‘<br> $obj is after setname is: <br> ‘;
print_r($obj);
Then the output will be
$obj is now : Employee Object ( [eid:Employee:private] => [ename:Employee:private] => )
$obj is after setid is:
Employee Object ( [eid:Employee:private] => 101 [ename:Employee:private] => )
$obj is after setname is:
Employee Object ( [eid:Employee:private] => 101 [ename:Employee:private] => Vipul )
- In the above code, we code property $eid and $ename is private so it can be accessible by public functions geteid, seteid, getename and setname. This is the practical implementation of encapsulation as property can only set and/or get by public method only.
- For example: if you code
- $obj->eid = 10; or
- $obj->ename = ‘Vimal’;
- Will generate an error.
- If you make property public then you can directly access it outside the class.
- For example:
public $ename;
$obj->ename = ‘Vimal’;
echo $obj->getename();
- Will work and display Vimal as output.
- Following code shows how constructor is used to initialize property value when object initiating from the class Employee.
<?php
class Employee
{
private $eid, $ename; // properties of a class Employee
public function __construct($eid,$ename)
{
$this->eid = $eid;
$this->ename = $ename;
}
// Getter and setter to set properties of object
public function geteid() //get method to get employeeid
{
return $this->eid;
}
public function seteid($value) //set method to set employeeid
{
$this->eid = $value;
}
public function getename()
{
return $this->ename;
}
public function setename($value)
{
$this->ename = $value;
}
}
$obj = new Employee(101,’Vipul’);
echo ‘<br> $obj is now : ‘;
print_r($obj);
$obj2 = new Employee(110,’Dhaval’);
echo ‘<br> $obj2 is now : ‘;
print_r($obj2);
echo ‘<br>’;
$obj2->seteid(102);
echo ‘<br> $obj2 is after setid is: <br> ‘;
print_r($obj2);
$obj2->setename(‘Vimal’);
echo ‘<br> $obj2 is after setname is: <br> ‘;
print_r($obj2);
?>
Then the output is:
$obj is now : Employee Object ( [eid:Employee:private] => 101 [ename:Employee:private] => Vipul )
$obj2 is now : Employee Object ( [eid:Employee:private] => 110 [ename:Employee:private] => Dhaval )
$obj2 is after setid is:
Employee Object ( [eid:Employee:private] => 102 [ename:Employee:private] => Dhaval )
$obj2 is after setname is:Employee Object ( [eid:Employee:private] => 102 [ename:Employee:private] => Vimal)
you can view video on OOP – I in PHP |
Reference:
1. Luke Welling, Laura Thomson: PHP and MySQL Web Development, Pearson,
2. W. Jason Gilmore: Beginning PHP and MySQL 5 From Novice to Professional,Apress
3. Elizabeth Naramore, Jason Gerner, Yann Le Scouarnec, Jeremy Stolz, Michael K.Glass: Beginning PHP5,apache, and MySQL Web Development, Wrox,
4. Robin Nixon: Learning PHP, MySQL, and JavaScript, O’Reilly Media
5. Ed Lecky-Thompson, Heow Eide-Goodman, Steven D. Nowicki, Alec Cove:Professional PHP, Wrox
6. Tim Converse, Joyce Park, Clark Morgan: PHP5 and MySQL Bible
7. Joel Murach, Ray Harris: Murach’s PHP and MySQL, Shroff/Murach
8. Ivan Bayross, Web Enabled Commercial Application Development Using HTML/Javascript/DHTML/PHP , BPB Publications
9. Julie C. Meloni, Sams Teach Yourself PHP, MySQL and Apache All in One, Sams
10. Larry Ullman, PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide,Pearson Education
11. http://www.php.net/
12. http://www.w3schools.com/
13. http://www.tutorialspoint.com/
14. https://docs.oracle.com/javase/tutorial/java/concepts/
15. http://www.tutorialspoint.com/cplusplus/cpp_object_oriented.htm
16. http://www.tutorialspoint.com/php/php_object_oriented.htm
17. http://inchoo.net/dev-talk/understanding-phps-oop-basic-terms-explained/