You are on page 1of 7

OBJECT ORIENDTED PROGRAMMING IN PHP

We can imagine our universe made of different objects like sun, earth, moon etc. Similarly we can imagine our car made of
different objects like wheel, steering, gear etc. Same way there is object oriented programming concepts which assume everything
as an object and implement a software using different objects.
Object Oriented Concepts:
Before we go in detail, lets define important terms related to Object Oriented Programming.
Class: his is a programmer!defined datatype, which includes local functions as well as local data. "ou can think of a
class as a template for making many instances of the same kind #or class$ of object.
Object: %n individual instance of the data structure defined by a class. "ou define a class once and then make many
objects that belong to it. Objects are also known as instance.
Member Variable: hese are the variables defined inside a class. his data will be invisible to the outside of the class
and can be accessed via member functions. hese variables are called attribute of the object once an object is created.
Member function: hese are the function defined inside a class and are used to access object data.
Inheritance: When a class is defined by inheriting e&isting function of a parent class then it is called inheritance. 'ere
child class will inherit all or few member functions and variables of a parent class.
Parent class: % class that is inherited from by another class. his is also called a base class or super class.
Child Class: % class that inherits from another class. his is also called a subclass or derived class.
Polymorphism: his is an object oriented concept where same function can be used for different purposes. (or e&ample
function name will remain same but it make take different number of arguments and can do different task.
Overloading: a type of polymorphism in which some or all of operators have different implementations depending on the
types of their arguments. Similarly functions can also be overloaded with different implementation.
Data Abstraction: %ny representation of data in which the implementation details are hidden #abstracted$.
ncapsulation: refers to a concept where we encapsulate all the data and member functions together to form an object.
Constructor: refers to a special type of function which will be called automatically whenever there is an object formation
from a class.
Destructors: refers to a special type of function which will be called automatically whenever an object is deleted or goes
out of scope.
Defining PHP Classes:
he general form for defining a new class in P'P is as follows)
<?php
class phpClass{
var $var1;
var $var2 = "constant string";
function myfunc ($arg1, $arg2) {
!!"
#
!!"
#
?$
'ere is the description of each line)
he special form class, followed by the name of the class that you want to define.
% set of braces enclosing any number of variable declarations and function definitions.
*ariable declarations start with the special form var, which is followed by a conventional + variable name, they may also
have an initial assignment to a constant value.
(unction definitions look much like standalone P'P functions but are local to the class and will be used to set and access
object data.
!ample:
'ere is an e&ample which defines a class of Books type)
<?php
class %oo&s{
'( )*m+*r varia+l*s ('
var $pric*;
var $titl*;
'( )*m+*r functions ('
function s*t,ric*($par){
$this-$pric* = $var;
#
function g*t,ric*(){
*cho $this-$pric* !"<+r'$";
#
function s*t.itl*($par){
$this-$titl* = $par;
#
function g*t.itl*(){
*cho $this-$titl* !" <+r'$";
#
#
?$
he variable "this is a special variable and it refers to the same object ie. itself.
Creating Objects in PHP
Once you defined your class, then you can create as many objects as you like of that class type. (ollowing is an e&ample of how to
create object using ne# operator.
$physics = n*/ %oo&s;
$maths = n*/ %oo&s;
$ch*mistry = n*/ %oo&s;
'ere we have created three objects and these objects are independent of each other and they will have their e&istance separately.
-e&t we will see how to access member function and process member variables.
Calling Member Functions
%fter creating your objects, you will be able to call member functions related to that object. One member function will be able to
process member variable of related object only.
(ollowing e&ample shows how to set title and prices for the three books by calling member functions.
$physics-$s*t.itl*( ",hysics for 0igh 1chool" );
$ch*mistry-$s*t.itl*( "23vanc*3 Ch*mistry" );
$maths-$s*t.itl*( "2lg*+ra" );
$physics-$s*t,ric*( 14 );
$ch*mistry-$s*t,ric*( 15 );
$maths-$s*t,ric*( 6 );
-ow you call another member functions to get the values set by in above e&ample)
$physics-$g*t.itl*();
$ch*mistry-$g*t.itl*();
$maths-$g*t.itl*();
$physics-$g*t,ric*();
$ch*mistry-$g*t,ric*();
$maths-$g*t,ric*();
his will produce follwoing result)
,hysics for 0igh 1chool
23vanc*3 Ch*mistry
2lg*+ra
14
15
6
Constructor Functions:
.onstructor (unctions are special type of functions which are called automatically whenever an object is created. So we take full
advantage of this behaviour, by initiali/ing many things through constructor functions.
P'P provides a special function called $$construct%& to define a constructor. "ou can pass as many as arguments you like into the
constructor function.
(ollowing e&ample will create one constructor for Books class and it will initiali/e price and title for the book at the time of object
creation.
function 77construct( $par1, $par2 ){
$this-$pric* = $par1;
$this-$titl* = $par2;
#
-ow we don0t need to call set function separately to set price and title. We can initiali/e these two member variables at the time of
object creation only. .heck following e&ample below)
$physics = n*/ %oo&s( ",hysics for 0igh 1chool", 14 );
$maths = n*/ %oo&s ( "23vanc*3 Ch*mistry", 15 );
$ch*mistry = n*/ %oo&s ("2lg*+ra", 6 );
'( 8*t thos* s*t valu*s ('
$physics-$g*t.itl*();
$ch*mistry-$g*t.itl*();
$maths-$g*t.itl*();
$physics-$g*t,ric*();
$ch*mistry-$g*t,ric*();
$maths-$g*t,ric*();
his will produce following result)
,hysics for 0igh 1chool
23vanc*3 Ch*mistry
2lg*+ra
14
15
6
Destructor:
1ike a constructor function you can define a destructor function using function $$destruct%&. "ou can release all the resourceses
with!in a destructor.
Inheritance:
P'P class definitions can optionally inherit from a parent class definition by using the e&tends clause. he synta& is as follows)
class Chil3 *9t*n3s ,ar*nt {
<3*finition +o3y$
#
he effect of inheritance is that the child class #or subclass or derived class$ has the following characteristics)
%utomatically has all the member variable declarations of the parent class.
%utomatically has all the same member functions as the parent, which #by default$ will work the same way as those
functions do in the parent.
(ollowing e&ample inherit Books class and adds more functionality based on the re2uirement.
class :ov*l *9t*n3s %oo&s{
var pu+lish*r;
function s*t,u+lish*r($par){
$this-$pu+lish*r = $par;
#
function g*t,u+lish*r(){
*cho $this-$pu+lish*r! "<+r '$";
#
#
-ow apart from inherited functions, class -ovel keeps two additional member functions.
Function Overriding:
(unction definitions in child classes override definitions with the same name in parent classes. 3n a child class, we can modify the
definition of a function inherited from parent class.
3n the follwoing e&ample getPrice and getitle functions are overriden to retrun some values.
function g*t,ric*(){
*cho $this-$pric* ! "<+r'$";
r*turn $this-$pric*;
#
function g*t.itl*(){
*cho $this-$titl* ! "<+r'$";
r*turn $this-$titl*;
#
Public Members:
4nless you specify otherwise, properties and methods of a class are public. hat is to say, they may be accessed in three possible
situations)
(rom outside the class in which it is declared
(rom within the class in which it is declared
(rom within another class that implements the class in which it is declared
ill now we have seen all members as public members. 3f you wish to limit the accessibility of the members of a class then you
define class members as private or protected.
Private members:
By designating a member private, you limit its accessibility to the class in which it is declared. he private member cannot be
referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class.
% class member can be made private by using private keyword infront of the member.
class )yClass {
privat* $car = "s&o3a";
$3riv*r = "1;<";
function 77construct($par) {
'' 1tat*m*nts h*r* run *v*ry tim*
'' an instanc* of th* class
'' is cr*at*3!
#
function my,u+lic=unction() {
r*turn(">?m visi+l*@");
#
privat* function my,rivat*=unction() {
r*turn(">?m not visi+l* outsi3*@");
#
#
When MyClass class is inherited by another class using e&tends, myPublic(unction#$ will be visible, as will +driver. he e&tending
class will not have any awareness of or access to myPrivate(unction and +car, because they are declared private.
Protected members:
% protected property or method is accessible in the class in which it is declared, as well as in classes that e&tend that class.
Protected members are not available outside of those two kinds of classes. % class member can be made protected by
using protected keyword infront of the member.
'ere is different version of 5y.lass)
class )yClass {
prot*ct*3 $car = "s&o3a";
$3riv*r = "1;<";
function 77construct($par) {
'' 1tat*m*nts h*r* run *v*ry tim*
'' an instanc* of th* class
'' is cr*at*3!
#
function my,u+lic=unction() {
r*turn(">?m visi+l*@");
#
prot*ct*3 function my,rivat*=unction() {
r*turn(">?m visi+l* in chil3 class@");
#
#
Interfaces:
3nterfaces are defined to provide a common function names to the implementors. 6ifferent implementors can implement those
interfaces according to theri re2uirements. "ou can say, interfaces are skeltons which are implemented by developers.
%s of P'P7, it is possible to define an interface, like this)
int*rfac* )ail {
pu+lic function s*n3)ail();
#
hen, if another class implemented that interface, like this)
class ;*port impl*m*nts )ail {
'' s*n3)ail() A*finition go*s h*r*
#
Constants:
% constant is somewhat like a variable, in that it holds a value, but is really more like a function because a constant is immutable.
Once you declare a constant, it does not change.
6eclaring one constant is easy, as is done in this version of 5y.lass)
class )yClass {
const r*Buir*3)argin = 1!6;
function 77construct($incomingCalu*) {
'' 1tat*m*nts h*r* run *v*ry tim*
'' an instanc* of th* class
'' is cr*at*3!
#
#
3n this class, re2uired5argin is a constant. 3t is declared with the keyword const, and under no circumstances can it be changed to
anything other than 8.9. -ote that the constant0s name does not have a leading +, as variable names do.
Abstract Classes:
%n abstract class is one that cannot be instantiated, only inherited. "ou declare an abstract class with the keyword abstract, like
this)
When inheriting from an abstract class, all methods marked abstract in the parent0s class declaration must be defined by the child,
additionally, these methods must be defined with the same visibillity.
a+stract class )y2+stractClass {
a+stract function my2+stract=unction() {
#
#
-ote that function definitions inside an abstract class must also be preceded by the keyword abstract. 3t is not legal to have
abstract function definitions inside a non!abstract class.
Static Keyword:
6eclaring class members or methods as static makes them accessible without needing an instantiation of the class. % member
declared as static can not be accessed with an instantiated class object #though a static method can$.
ry out following e&ample)
<?php
class =oo
{
pu+lic static $my7static = ?foo?;
pu+lic function staticCalu*() {
r*turn s*lfDD$my7static;
#
#
print =ooDD$my7static ! "En";
$foo = n*/ =oo();
print $foo-$staticCalu*() ! "En";
Final Keyword:
P'P 7 introduces the final keyword, which prevents child classes from overriding a method by prefi&ing the definition with final. 3f
the class itself is being defined final then it cannot be e&tended.
(ollowing e&ample results in (atal error) .annot override final method Base.lass))moreesting#$
<?php
class %as*Class {
pu+lic function t*st() {
*cho "%as*ClassDDt*st() call*3<+r$";
#

final pu+lic function mor*.*sting() {
*cho "%as*ClassDDmor*.*sting() call*3<+r$";
#
#
class Chil3Class *9t*n3s %as*Class {
pu+lic function mor*.*sting() {
*cho "Chil3ClassDDmor*.*sting() call*3<+r$";
#
#
?$
Calling parent constructors:
3nstead of writing an entirely new constructor for the subclass, let0s write it by calling the parent0s constructor e&plicitly and then
doing whatever is necessary in addition for instantiation of the subclass. 'ere0s a simple e&ample)
class :am*
{
var $7first:am*;
var $7last:am*;
function :am*($first7nam*, $last7nam*)
{
$this-$7first:am* = $first7nam*;
$this-$7last:am* = $last7nam*;
#
function to1tring() {
r*turn($this-$7last:am* !", " !$this-$7first:am*);
#
#
class :am*1u+1 *9t*n3s :am*
{
var $7mi33l*>nitial;
function :am*1u+1($first7nam*, $mi33l*7initial, $last7nam*) {
:am*DD:am*($first7nam*, $last7nam*);
$this-$7mi33l*>nitial = $mi33l*7initial;
#
function to1tring() {
r*turn(:am*DDto1tring() ! " " ! $this-$7mi33l*>nitial);
#
#
3n this e&ample, we have a parent class #-ame$, which has a two!argument constructor, and a subclass #-ameSub8$, which has a
three!argument constructor. he constructor of -ameSub8 functions by calling its parent constructor e&plicitly using the )) synta&
#passing two of its arguments along$ and then setting an additional field. Similarly, -ameSub8 defines its nonconstructor toString#$
function in terms of the parent function that it overrides.
'O(: % constructor can be defined with the same name as the name of a class. 3t is defined in above e&ample.

You might also like