Object Oriented Programming (OOP) in PHP
Object Oriented Programming (OOP) in PHP
Paradigm: is a fundamental style or approach to programming that guides the way you design and structure your
code. It represents a set of principles, concepts, and practices for developing software.
Major features of OOP in PHP
Classes and Objects: A class is a blueprint or template for creating objects, while an
object is an instance of a class. Classes define the properties (attributes) and methods
(functions) that objects of that class will possess. You can define a class using the class
keyword and you can create an instance of a class using the new keyword. A blueprint
typically refers to a detailed plan or technical drawing that outlines the design,
structure, or specifications of a building, object, or system. It serves as a visual
representation of how something should be constructed, assembled, or
implemented.
Encapsulation: Encapsulation is the practice of bundling data (properties) and related
behaviors (methods) together within a class. It allows you to control access to the
class members by using access modifiers such as public, private, and protected.
Inheritance: Inheritance allows you to create a new class (child class) based on an
existing class (parent class). The child class inherits the properties and methods of the
parent class, and it can also override or extend the functionality of the parent class.
Polymorphism: Polymorphism refers to the ability to use objects of different classes
interchangeably if they share a common interface or base class. 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. PHP supports polymorphism through method overriding
Abstraction: Abstraction involves creating abstract classes or interfaces that define a
common interface for a group of related objects. Abstract classes cannot be
instantiated and are meant to be extended by concrete (non-abstract) classes.
Interfaces define a contract that specifies a set of methods a class must implement,
without providing any implementation details. Any representation of data in which
the implementation details are hidden (abstracted).
Constructors and Destructors: Constructors are special methods that are
automatically called when an object is created. They are used to initialize object
properties or perform setup tasks. Destructors are called when an object is no longer
referenced or goes out of scope, and they can be used to perform cleanup tasks.
Interface: defines the methods that must be implemented by any class that claims
to implement that interface. It acts as a blueprint for classes, ensuring that they
provide specific functionality. To define an interface in PHP, you use the interface
keyword and to implement an interface in a class, you use the implements
keyword.Interfaces allow you to specify what methods a class should implement. Interfaces
make it easy to use a variety of different classes in the same way.
Advantages of OOP
Modularity: OOP allows you to break down complex problems into smaller, more manageable modules
known as classes. Each class encapsulates data and related behaviors, making it easier to understand,
modify, and maintain the code. This modularity promotes code reusability and reduces code
redundancy.
Code reusability: Inheritance, one of the fundamental concepts of OOP, allows you to create new
classes by inheriting properties and behaviors from existing classes. This promotes code reuse and
helps save development time. You can create a base class with common features and then derive
multiple specialized classes from it, adding or overriding specific functionality as needed.
Encapsulation: OOP emphasizes encapsulation, which means bundling data and the methods that
operate on that data within a single unit (a class). It provides data hiding, preventing direct access to
the internal state of an object. Instead, external code interacts with objects through well-defined
interfaces (public methods), improving security and reducing the likelihood of unintended data
modifications.
OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code easier to maintain,
modify and debug.
The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You
should extract out the codes that are common for the application, and place them at a
OOP helps to keep the PHP code DRY "Don't Repeat Yourself",
single place and reuse them instead of repeating it.
and makes the code easier to maintain, modify and debug
Abstraction: OOP allows you to create abstract representations of real-world objects or
concepts in the form of classes. These classes can capture the essential properties and
behaviors of objects, while hiding the unnecessary implementation details. Abstraction
simplifies problem-solving by providing a high-level view and focusing on the relevant aspects
of the system.
Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a
common superclass. It enables you to write code that can work with objects of multiple types,
providing flexibility and extensibility. Polymorphism is often achieved through method
overriding and interfaces, allowing you to write generic code that can be reused with different
implementations.
Maintainability: OOP promotes code organization and improves maintainability. The modular
structure of classes makes it easier to locate and update specific sections of code. Changes
made in one part of the system are less likely to affect other parts, reducing the potential for
unintended side effects. This makes code maintenance, debugging, and testing more efficient
and less error-prone.
Collaboration: OOP facilitates collaboration among programmers working on the same project.
The ability to create classes with well-defined interfaces allows different developers to work
independently on different components, as long as they adhere to the contract defined by the
class interfaces. This promotes teamwork, code integration, and parallel development.
Disadvantages of OOP
Steeper learning curve: OOP introduces new concepts and terminology that can be
challenging for beginners to grasp. Understanding principles such as classes, objects,
inheritance, and polymorphism requires a shift in thinking and can take time to fully
comprehend.
Overhead: OOP can introduce additional overhead in terms of memory consumption
and performance. Objects in OOP carry additional information, such as class metadata
and method tables, which can increase memory usage. Additionally, dynamic dispatch,
a mechanism used in OOP for method invocation, can result in slower execution
compared to static dispatch used in procedural programming.
Complexity: OOP encourages breaking down a problem into smaller, more manageable
objects. However, as the number of objects and their interactions increase, the
complexity of the codebase can grow rapidly. It can become challenging to understand
the relationships between objects and maintain the codebase effectively.
Inheritance limitations: Inheritance, a key feature of OOP, allows for code reuse and
creating hierarchical relationships between classes. However, it can lead to problems
such as the "diamond problem" where multiple inheritance hierarchies can cause
ambiguity and confusion. Inheritance can also result in a tightly coupled codebase,
making it harder to modify and extend classes in the future.
Difficulty in parallel programming: OOP can pose challenges in parallel and
concurrent programming. Objects encapsulate data and behavior, making it
harder to parallelize certain operations. Coordinating the synchronization
and communication between objects in a multi-threaded environment can
be complex and prone to issues.
Overuse of abstraction: OOP encourages abstraction, which can be beneficial
for managing complexity. However, excessive abstraction can make the
codebase harder to understand, especially for newcomers to the project. Too
many layers of abstraction can obscure the underlying implementation
details and hinder debugging and maintenance efforts.
Performance overhead of dynamic typing: Some OOP languages, such as
Python, support dynamic typing, where the type of an object is determined
at runtime. While dynamic typing provides flexibility, it can result in a
performance overhead compared to statically typed languages. Dynamic
type checks and dispatching can slow down the execution of programs.
Access Modifiers
In object-oriented programming (OOP), an access modifier is a keyword or declaration that specifies the
accessibility or visibility of a class member (such as a variable, method, or class itself) from other parts of
the program. Properties and methods can have access modifiers which control where they can be
accessed.
There are three access modifiers:
public: The public access modifier allows unrestricted access to the member from any part of the
program. It means that the member can be accessed and used by any other class or code module. the
property or method can be accessed from everywhere. This is default.
For example, a public method can be called from any other class, and a public variable can be read or
modified directly.
private: the property or method can ONLY be accessed within the class. The private access modifier
restricts access to the member within the same class. It means that the member is only accessible from
within the class itself. Private members cannot be accessed or modified directly by other classes or code
modules. This encapsulation helps to protect the internal implementation details of a class.
protected: the property or method can be accessed within the class and by classes derived from that
class. The protected access modifier allows access to the member within the same class and its
subclasses (derived classes or child classes). Protected members are not accessible outside of the class
hierarchy. They provide a level of encapsulation and are often used to expose certain behavior or data to
derived classes while still keeping them hidden from other classes.
Class and Object
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.
In a class, variables are called properties and functions are called
methods.
Objects is instance of a class and is created using the new keyword.
This is the blueprint of the construction work that is class, and the houses and apartments made
by this blueprint are the objects
Syntax to Create Class in PHP
<?php
class MyClass
{
// Class properties and methods go here
}
?>
The $this variable
To access an object's properties and methods from within the methods
of the same object we use the $this special variable.
Object
class NumberAdd
{
// Method to add two numbers
public function addNumbers($num1, $num2) {
$sum = $num1 + $num2;
echo "The sum of $num1 and $num2 is= $sum "; Output
}
}
// Create a new NumberAdd object
$addition = new NumberAdd();
echo $apple->get_name();
echo '<br>';
echo $banana->get_name();
<?php
class Fruit
{
// Properties
public $name;
public $color;
// Methods
public function set_name($name)
{
$this->name = $name;
}
Output
Program to calculate simple interest
<?php
class interestCalculator
{
public $rate;
public $duration;
public $capital;
public function calculateInterest()
{
return ($this->rate * $this->duration * $this->capital) / 100;
}
}// Creating various object of class interestCalculator to calculate
interest on various amount
$calculator1 = new InterestCalculator();
$calculator2 = new InterestCalculator();
$calculator1->rate = 3;
$calculator1->duration = 2;
$calculator1->capital = 300;
$calculator2->rate = 3.2;
$calculator2->duration = 3;
$calculator2->capital = 400;
$interest1 = $calculator1->calculateInterest();
$interest2 = $calculator2->calculateInterest();
echo "Your interest on capital $calculator1->capital
with rate $calculator1->rate for duration
$calculator1->duration is $interest1 <br/> ";
echo "Your interest on capital $calculator2->capital
with rate $calculator2->rate for duration
$calculator2->duration is $interest2 <br/> ";
?>
Please run above code in browser. You will
get following output.
Inheritance
Inheritance is the phenomenon by which a child class can inherit all the
properties and characteristics of the parent class.
Inheritance in OOP = When a class derives from another class.
The child class will inherit all the public and protected properties and
methods from the parent class. In addition, it can have its own
properties and methods.
An inherited class is defined by using the extends keyword.
PHP offers mainly three types of inheritance based on their functionality.
These three types are as follows:
Single Inheritance: Single inheritance is the most basic or fundamental
type of inheritance offered by PHP. There is only one base class and one
sub/derived class in a single inheritance and the subclass is directly
inherited from the base class.
Hierarchical Inheritance: As the name suggests, the hierarchical
inheritance adopts a tree-like structure, where multiple derived classes
are inherited from the base class.
Multilevel Inheritance: Multilevel inheritance is the third type of
inheritance supported in PHP. It occurs at different levels. Here, one base
class is inherited by a derived class, then that derived class is inherited by
other derived classes, and so on.
Single Inheritance:
Multilevel Inheritance
Hierarchical Inheritance
The Syntax for Inheriting a Class in PHP
Depicted below is the syntax that is used to extend a base class in PHP.
}
The keyword extends is used to define a derived or child class in PHP.
derived_class_name: It specifies the name of the derived or the child class. The
child class, also known as a subclass, inherits its salient features or
characteristics from its parent class. There can be one or over one derived class
that inherits from the same base class depending on what type of inheritance is
performed. There are three visibility modes supported in PHP: Public, Private,
and Protected, which specify how the derived class will inherit what.
base_class_name: It specifies the name of the base or the parent class from
which the child class is inheriting its properties. A base class is also known as a
parent class because all the classes that are termed as derived classes or child
classes inherit their properties from the base class. There can be one or more
base classes in a program, depending upon the type of inheritance. For
instance, in a single-level inheritance, there will be one base class for one child
class, but in a multilevel inheritance, one child class can inherit from over one
base class in more than one level.
Eg:1
<?php
class a
{
public function fun1() Output
{
echo 'Welcome to inheritance'; }
}
class b extends a
{
public function fun2()
{
echo 'PHP for Year 1';}
}
$obj = new b();
$obj->fun1();
?>
Eg 2
<?php
class demo
{
public function display()
{
echo 'Rwanda coding Academy ';
}
}
class demo1 extends demo Output
{
public function view()
{
echo 'is Hybrid School ';
}
}
$obj = new demo1();
$obj->display();
$obj->view();
?>
Eg3
<?php
// parent class
class Human
{
// public property name
public $name;
// public function walk
public function walk()
{
echo $this->name.' is walking...<br/>';
}
// child class
class Female extends Human Output
{
// No code in child
}
echo $obj->price;
echo '<br>';
$obj->printMessage();
$obj->print();
?>
Private:
class Jewellery
{
private $price = 'We have a fixed price of 100000FRW';
// derived class
$obj->show();
$obj->printPrice();
?>
Protected
echo '<br>';
} Output
}
$obj->total();
$obj->printInvoice();
?>
Exercise
1.Write superclass called Animal with color,name,age properties and
create sub class called Dog which access the properties of superclass.