Chap4 OOP in PHP
Chap4 OOP in PHP
Object-Oriented PHP
Procedural programming is about writing procedures or functions that perform operations on the
data, while object-oriented programming is about creating objects that contain both data and
functions.
Class − This is a programmer-defined data type, which includes local functions as well as
local data. You can think of a class as a template for making many instances of the same
kind (or class) of object.
Object − An individual instance of the data structure defined by a class. You define a
class once and then make many objects that belong to it. Objects are also known as
instance.
Member Variable − These are the variables defined inside a class. This data will be
invisible to the outside of the class and can be accessed via member functions. These
variables are called attribute of the object once an object is created.
Member function − These are the function defined inside a class and are used to access
object data.
Inheritance − When a class is defined by inheriting existing function of a parent class
then it is called inheritance. Here child class will inherit all or few member functions and
variables of a parent class.
Parent class − A class that is inherited from by another class. This is also called a base
class or super class.
Child Class − A class that inherits from another class. This is also called a subclass or
derived class.
Polymorphism − This is an object oriented concept where same function can be used for
different purposes. For example function name will remain same but it 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 − Any representation of data in which the implementation details are
hidden (abstracted).
Encapsulation − 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.
Destructor − refers to a special type of function which will be called automatically
whenever an object is deleted or goes out of scope.
Class
A class is an entity that determines how an object will behave and what the object will
contain. In other words, it is a blueprint or a set of instruction to build a specific type of
object.
A class is defined by using the class keyword, followed by the name of the class and a pair of
curly braces ({}). All its properties and methods go inside the braces:
<?php
class Class_Name
{
// data memebers
//member function
}
?>
Objects
Classes are nothing without objects! We can create multiple objects from a class. Each object has
all the properties and methods defined in the class, but they will have different property values.
Syntax:
$object_name_= new class_name;
<?php
class Person
{
public $firstName;
public $lastName;
public function getFullName()
{
return $this->firstName . ' ' . $this->lastName;
}
A constructor allows you to initialize an object's properties upon creation of the object.
If you create a __construct() function, PHP will automatically call this function when you create
an object from a class.
Notice that the construct function starts with two underscores (__)!
Constructor types:
Default Constructor:It has no parameters, but the values to the default constructor can
be passed dynamically.
Parameterized Constructor: It takes the parameters, and also you can pass different
values to the data members.
Copy Constructor: It accepts the address of the other objects as a parameter.
Example
<?php
class myclass
{
function __construct()
{
echo "object initialized";
}
}
$obj=new myclass();
?>
Output
object initialized
Parameterized Constructor: The constructor of the class accepts arguments or parameters.
The -> operator is used to set value for the variables. In the constructor method, you can assign
values to the variables during object creation.
<?php
class Employee
{
Public $name;
Public $position;
function __construct($name,$position)
{
// This is initializing the class properties
$this->name=$name;
$this->position=$position;
}
function show_details()
{
echo $this->name." : ";
echo "Your position is ".$this->profile."\n";
}
}
$employee_obj->show_details();
$employee2->show_details();
?>
Output:
Destructor is a method automatically as soon as garbage collector fins that a particular object has
no more references. In PHP, destructor method is named as __destruct. During shutdown
sequence too, objects will be destroyed. Destructor method doesn't take any arguments, neither
does it return any data type
<?php
class myclass
{
function __construct()
{
echo "object is initialized
";
}
function __destruct(){
echo "object is destroyed
";
}
}
$obj=new myclass();
?>
Output
object is initialized
object is destroyed
Inheritance
When a class derives from another class, it is known as inheritance. Here are some important
terms related to inheritance in PHP.
Parent Class – The class from which the other classes are derived is called parent class. It is
also known as base class.
Child Class – The class that is derived from another class is called child class. There are
some other names for it also like leaf class or derived class.
Syntax
class B extends A
where A is the base class (also called parent called) and B is called a subclass or child class. Child
class inherits public and protected methods of parent class.
Example
<?php
class A
{
//properties, constants and methods of class A
}
class B extends A
{
//public and protected methods inherited
}
?>
Types of Inheritance
1. Single Inheritance
PHP supports Single inheritance. Single inheritance is a concept in PHP in which only one class
can be inherited by a single class. We need to have two classes in between this process. One is the
base (parent) class, and the other is the child class.
<?php
class Base
{
function BaseFun()
{
echo "This is Base Class Function" . "<br/>";
}
}
$dObj->BaseFun();
$dObj->DerivedFun();
?>
Output:
This is Base Class Function
This is Derived Class Function
2. Multilevel Inheritance
PHP supports Multilevel Inheritance. In this type of inheritance, we will have more than 2
classes. In this type of inheritance, a parent class will be inherited by a child class then that child
class will be inherited by the child class.
<?php
class grandparent
{
function dis1()
{
echo "Grand-Parent" . "<br/>";
}
}
class parents extends grandparent
{
function dis2()
{
echo "Parents" . "<br/>";
}
}
class child extends parents
{
function dis3()
{
echo "Child" . "<br/>";
}
}
$obj=new child();
$obj->dis1();
$obj->dis2();
$obj->dis3();
?>
Output:
Grand-Parent
Parents
Child
3. Hierarchical Inheritance
PHP supports Hierarchical inheritance. Hierarchical inheritance is the type of inheritance in
which a program consists of a single parent and more than one child class.
<?php
class Base
{
function BaseFun()
{
echo "BaseFun() called<br>";
}
}
In PHP, access modifiers play an important role in inheritance, as they define the visibility
and accessibility of properties and methods in the class hierarchy. There are three access
modifiers available in PHP:
Public:
The public access modifier allows properties and methods to be accessed from anywhere,
including outside the class, subclasses, and instances of the class. Public members are
inherited by child classes and can be overridden or extended.
Protected:
The protected access modifier limits the visibility of properties and methods to the class
itself and its subclasses. Protected members can be accessed within the class and its
subclasses, but not from outside the class hierarchy. Protected members are inherited by
child classes and can be overridden or extended.
Private:
The private access modifier restricts the visibility of properties and methods to the class
where they are defined. Private members cannot be accessed or inherited by child classes
or instances of the class. They are only accessible within the class itself. Therefore, private
members cannot be overridden or extended in child classes.
<?php
class parentclass
{
public function publicmethod()
{
echo "This is public method of parent class" ;
}
protected function protectedmethod()
{
echo "This is protected method of parent class" ;
}
private function privatemethod()
{
echo "This is private method of parent class" ;
}
}
class childclass extends parentclass
{
public function childmethod()
{
$this->protectedmethod();
//$this->privatemethod(); //this will produce error
}
}
$obj=new childclass();
$obj->publicmethod();
$obj->childmethod();
?>
Output:
This is public method of parent class
This is protected method of parent class
PHP Fatal error: Uncaught Error: Call to private method parentclass::privatemethod()
from context 'childclass'
Interface
An Interface is defined just like a class is defined but with the class keyword
replaced by the interface keyword.
An interface allows unrelated classes to implement the same set of methods,
regardless of their positions in the class inheritance hierarchy.
An interface can model multiple inheritances because a class can implement more
than one interface whereas it can extend only one class.
An interface can define method names and arguments, but not the contents of the
methods.
Any classes implementing an interface must implement all methods defined by the
interface.
Syntax
interface <interface_name>
{
}
<?php
interface a
{
public function dis1();
}
interface b
{
public function dis2();
}
?>
Output:
method 1...method 2…
Abstract Class
Abstract classes and methods are when the parent class has a named method, but need its
child class(es) to fill out the tasks.
An abstract class is a class that contains at least one abstract method. An abstract method
is a method that is declared, but not implemented in the code.
o Classes extending an abstract class must implement all of the abstract methods
defined in the abstract class.
o An abstract class is declared the same way as classes with the addition of the
'abstract' keyword.
SYNTAX:
Output:
The main purpose of using exception handling is to maintain the normal execution of
the application.
What is an Exception?
Syntax
try
{
// Protected code
} catch (ExceptionName e1)
{
// Catch block
}
PHP provides a powerful mechanism, exception handling. It allows you to handle runtime
errors such as IOException, SQLException, ClassNotFoundException, and more. A most
popular example of exception handling is - divide by zero exception, which is an
arithmetic exception.
try -
The try block contains the code that may have an exception or where an exception can
arise. When an exception occurs inside the try block during runtime of code, it is caught
and resolved in catch block. The try block must be followed by catch or finally block. A
try block can be followed by minimum one and maximum any number of catch blocks.
catch -
The catch block contains the code that executes when a specified exception is thrown. It is
always used with a try block, not alone. When an exception occurs, PHP finds the
matching catch block.
throw -
It is a keyword used to throw an exception. It also helps to list all the exceptions that a
function throws but does not handle itself.
finally -
The finally block contains a code, which is used for clean-up activity in PHP. Basically, it
executes the essential code of the program.
Example
<?php
class DivideByZeroException extends Exception { }
class DivideByNegativeNoException extends Exception { }
function checkdivisor($dividend, $divisor)
{
try
{
if ($divisor == 0)
{
throw new DivideByZeroException;
}
else if ($divisor < 0)
{
throw new DivideByNegativeNoException;
}
else
{
$result = $dividend / $divisor;
echo "Result of division = $result </br>";
}
}
catch (DivideByZeroException $dze)
{
echo "Divide by Zero Exception! </br>";
}
catch (DivideByNegativeNoException $dnne)
{
echo "Divide by Negative Number Exception </br>";
}
catch (Exception $ex)
{
echo "Unknown Exception";
}
}
checkdivisor(18, 3);
checkdivisor(34, -6);
checkdivisor(27, 0);
?>
Output:
Result of division = 6
Divide by Zero Exception!
Divide by Negative Number Exception!
Final classes
o In PHP, Final keyword is applicable to only class and class methods. We cannot
declare as Final in PHP.
o So if we declare class method as a Final then that method cannot be override by
the child class.
o Same as method if we declare class as a Final then that class cannot be extended
any more.
Example
<?php
class base
{
final public function dis1()
{
echo "Base class..";
}
}
class derived extends base
{
public function dis1()
{
echo "derived class";
}
}
$obj = new derived();
$obj->dis1();
?>
Output:
final class example
<?php
final Class BaseClass
{
function printData($val1,$val2)
{
$add=$val1+$val2;
echo "Sum of given no=".$s;
}
}
class Child extends BaseClass
{
function printData($val1,$val2)
{
$m=$val1*$val2;
echo "Multiplication of given no=".$m;
}
}
$obj= new Child();
$obj->printData(20,20);
?>
Output:
PHP Fatal error: Class Child may not inherit from final class (BaseClass)