UNIT III Classes and Objects:
Introduction to OOPS Concepts
As the name suggests, Object-Oriented Programming or OOPs refers to languages that use
objects in programming. Object-oriented programming aims to implement real-world entities
like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind
together the data and the functions that operate on them so that no other part of the code can
access this data except that function.
OOPs Concepts:
Class
Objects
Data Abstraction
Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message Passing
1. Class:
A class is a user-defined data type. It consists of data members and member functions, which
can be accessed and used by creating an instance of that class. It represents the set of
properties or methods that are common to all objects of one type. A class is like a blueprint
for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and
brands but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed limits, mileage
are their properties.
2. Object:
It is a basic unit of Object-Oriented Programming and represents the real-life entities. An
Object is an instance of a Class. When a class is defined, no memory is allocated but when it
is instantiated (i.e. an object is created) memory is allocated. An object has an identity, state,
and behavior. Each object contains data and code to manipulate the data. Objects can interact
without having to know details of each other’s data or code, it is sufficient to know the type
of message accepted and type of response returned by the objects.
For example “Dog” is a real-life Object, which has some characteristics like color, Breed,
Bark, Sleep, and Eats.
Object
3. Data Abstraction:
Data abstraction is one of the most essential and important features of object-oriented
programming. Data abstraction refers to providing only essential information about the data
to the outside world, hiding the background details or implementation. Consider a real-life
example of a man driving a car. The man only knows that pressing the accelerators will
increase the speed of the car or applying brakes will stop the car, but he does not know about
how on pressing the accelerator the speed is increasing, he does not know about the inner
mechanism of the car or the implementation of the accelerator, brakes, etc in the car. This is
what abstraction is.
4. Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism
that binds together code and the data it manipulates. In Encapsulation, the variables or data
of a class are hidden from any other class and can be accessed only through any member
function of their class in which they are declared. As in encapsulation, the data in a class is
hidden from other classes, so it is also known as data-hiding.
Consider a real-life example of encapsulation, in a company, there are different sections like
the accounts section, finance section, sales section, etc. The finance section handles all the
financial transactions and keeps records of all the data related to finance. Similarly, the sales
section handles all the sales-related activities and keeps records of all the sales. Now there
may arise a situation when for some reason an official from the finance section needs all the
data about sales in a particular month. In this case, he is not allowed to directly access the
data of the sales section. He will first have to contact some other officer in the sales section
and then request him to give the particular data. This is what encapsulation is. Here the data
of the sales section and the employees that can manipulate them are wrapped under a single
name “sales section”.
5. Inheritance:
Inheritance is an important pillar of OOP(Object-Oriented Programming). The capability of
a class to derive properties and characteristics from another class is called Inheritance. When
we write a class, we inherit properties from other classes. So when we create a class, we do
not need to write all the properties and functions again and again, as these can be inherited
from another class that possesses it. Inheritance allows the user to reuse the code whenever
possible and reduce its redundancy.
6. Polymorphism:
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. For
example, A person at the same time can have different characteristics. Like a man at the same
time is a father, a husband, an employee. So the same person posses different behavior in
different situations. This is called polymorphism.
7. Dynamic Binding:
In dynamic binding, the code to be executed in response to the function call is decided at
runtime. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time. Dynamic Method Binding One of the main
advantages of inheritance is that some derived class D has all the members of its base class
B. Once D is not hiding any of the public members of B, then an object of D can represent B
in any context where a B could be used. This feature is known as subtype polymorphism.
8. Message Passing:
It is a form of communication used in object-oriented programming as well as parallel
programming. Objects communicate with one another by sending and receiving information
to each other. A message for an object is a request for execution of a procedure and therefore
will invoke a function in the receiving object that generates the desired results. Message
passing involves specifying the name of the object, the name of the function, and the
information to be sent.
Why do we need object-oriented programming
To make the development and maintenance of projects more effortless.
To provide the feature of data hiding that is good for security concerns.
We can solve real-world problems if we are using object-oriented programming.
It ensures code reusability.
It lets us write generic code: which will work with a range of data, so we don't have to
write basic stuff over and over again.
Visibility Controls
In PHP, visibility controls, also known as access modifiers, regulate the accessibility of class
members (properties and methods) from different parts of your code. PHP provides three
primary visibility keywords: public, protected, and private.
public:
o public members are accessible from anywhere. This includes within the class itself,
from any class that extends it (child classes), and from outside the class (e.g., when creating an
object and accessing its public members).
o This is the default visibility if no keyword is specified for a class member.
Code
class MyClass {
public $publicProperty = "I am public";
public function publicMethod() {
return "This is a public method.";
}
}
$obj = new MyClass();
echo $obj->publicProperty; // Accessible
echo $obj->publicMethod(); // Accessible
protected:
o protected members are accessible within the class where they are defined and within any
class that inherits from it (child classes).
o They are not accessible from outside the class or its descendants.
Code
class ParentClass {
protected $protectedProperty = "I am protected";
protected function protectedMethod() {
return "This is a protected method.";
}
}
class ChildClass extends ParentClass {
public function accessProtected() {
echo $this->protectedProperty; // Accessible within child class
echo $this->protectedMethod(); // Accessible within child class
}
}
$childObj = new ChildClass();
$childObj->accessProtected();
// echo $childObj->protectedProperty; // Error: Cannot access protected property
private:
o private members are the most restrictive. They are only accessible within the class where
they are defined.
o They are not accessible from outside the class, nor from any class that extends it.
Code
class AnotherClass {
private $privateProperty = "I am private";
private function privateMethod() {
return "This is a private method.";
}
public function accessPrivate() {
echo $this->privateProperty; // Accessible within the same class
echo $this->privateMethod(); // Accessible within the same class
}
}
$anotherObj = new AnotherClass();
$anotherObj->accessPrivate();
// echo $anotherObj->privateProperty; // Error: Cannot access private property
These visibility controls are fundamental to Object-Oriented Programming (OOP) in PHP,
promoting encapsulation and allowing developers to manage the access and modification of
class data and behavior effectively.
Creating Class and Object
In PHP, Object-Oriented Programming (OOP) makes it easier to organize and reuse code.
The two fundamental building blocks in OOP are classes and objects.
PHP Classes
A class in PHP is a blueprint for creating objects. It defines the properties (variables) and
methods (functions) that the objects created from the class will have. By using classes, we
can group related data and actions, making it easier to organize and manage our code.
In PHP, a class is defined using the class keyword, followed by the class name and curly
braces.
Syntax:
<?php
class Cars {
// PHP code goes here...
?>
Now, let us understand with the help of the example:
<?php
class Car {
public $brand, $model, $year;
function __construct($brand, $model, $year) {
$this->brand = $brand;
$this->model = $model;
$this->year = $year;
}
function displayInfo() {
echo "$this->brand $this->model, $this->year";
}
}
$car = new Car("Toyota", "Corolla", 2021);
$car->displayInfo();
?>
Output
Toyota Corolla, 2021
In this example:
The Car class is defined with three properties: $brand, $model, and $year.
The __construct() method initializes the properties when a new object of the Car class is
created, using the provided values.
$this keyword is used within a class to refer to the current object. It allows you to access
properties and methods of the current object from within the class.
The displayInfo() method is defined to print out the car's brand, model, and year.
A new object $car is created from the Car class, and values ("Toyota", "Corolla", 2021")
are passed to the constructor.
The displayInfo() method is called on the $car object to display the car's details: "Toyota
Corolla, 2021".
PHP Objects
An object is an instance of a class. When you create an object from the class, memory is
allocated, and the object can store data and perform actions defined in the class. To create an
object, we use the new keyword.
Syntax:
$objectName = new ClassName($value);
Now, let us understand with the help of the example:
<?php
class Car {
public $brand;
function __construct($brand) {
$this->brand = $brand;
}
function displayInfo() {
echo "Car brand: $this->brand";
}
}
$myCar = new Car("Toyota");
$myCar->displayInfo(); // Output: Car brand: Toyota
?>
Output
Car brand: Toyota
In this example:
The Car class has one property, $brand, and a method displayInfo() to display the car's
brand.
An object $myCar is created from the Car class with the brand "Toyota".
The displayInfo() method is called to show the car's brand.
Overloading, Constructor
In PHP, a constructor is a special method within a class, named __construct(), that is
automatically invoked when a new object of that class is created. Its primary purpose is to
initialize the object's properties and set its initial state.
Overloading in the traditional sense, as found in languages like Java or C++ where multiple
methods or constructors can share the same name but differ in their parameter lists, is not
directly supported in PHP. If multiple methods or constructors with the same name are defined
in a PHP class, the last definition will override any previous ones.
However, the concept of "overloading" in PHP refers to a different mechanism: dynamic
creation of properties and methods using magic methods. When an attempt is made to access
an undeclared or inaccessible property or method, specific magic methods are invoked:
__set($name, $value): Called when writing to an inaccessible property.
__get($name): Called when reading from an inaccessible property.
__isset($name): Called when isset() or empty() is used on an inaccessible property.
__unset($name): Called when unset() is used on an inaccessible property.
__call($name, $arguments): Called when invoking an inaccessible method.
__callStatic($name, $arguments): Called when invoking an inaccessible static method.
Simulating Constructor Overloading in PHP:
While direct constructor overloading is not possible, its functionality can be simulated using
various patterns:
Using func_get_args() within the single __construct() method: This allows checking the
number and types of arguments passed and handling different initialization logic accordingly.
class MyClass {
public function __construct() {
$args = func_get_args();
$numArgs = func_num_args();
if ($numArgs === 1 && is_string($args[0])) {
// Handle single string argument for initialization
} elseif ($numArgs === 2 && is_string($args[0]) && is_int($args[1])) {
// Handle two arguments (string, int) for initialization
}
}
}
Named Constructors (Factory Pattern): This involves creating static factory methods that
return new instances of the class, each handling a specific set of initialization parameters.
class MyClass {
private function __construct() {
// Private to enforce creation through static methods
}
public static function createFromId(int $id): self {
$instance = new self();
// Initialize based on ID
return $instance;
}
public static function createFromName(string $name): self {
$instance = new self();
// Initialize based on name
return $instance;
}
}
The constructor is marked private, meaning objects of this class cannot be created
using new MyClass() from outside the class.
Purpose: To enforce object creation only through the static methods defined below.
public static function createFromId(int $id) - This is a static method, so it can be called
without instantiating the class.
It accepts an integer $id as input.
It creates a new instance of MyClass internally using new self() (allowed here because
it's inside the class).
Returns the instance.
Destructors
A destructor is a special method in PHP that is automatically called when an object is
destroyed or goes out of scope. It is mainly used for cleaning up or releasing resources that
the object might have acquired during its lifetime, such as closing file handles or database
connections.
Syntax:
<?php
class ClassName {
public function __destruct() {
// Destructor code here
}
}
?>
class Database {
public $connection;
// Constructor to initialize the connection
public function __construct($hostname) {
$this->connection = "Connected to database at $hostname";
echo $this->connection;
}
// Destructor to close the connection
public function __destruct() {
echo "\nConnection closed.";
}
}
$db = new Database("localhost");
?>
Object Inheritance
Inheritance in PHP is the ability of a class (known as a child class or subclass) to derive
properties and methods from another class (known as a parent class or base class). Using
inheritance, you can extend existing classes and modify or add new functionalities without
changing the original code.
Syntax:
class ParentClass {
// Properties and methods
}
class ChildClass extends ParentClass {
// Additional or overridden properties and methods
}
Example:
<?php
class Animal {
public $name;
public function eat() {
echo "$this->name is eating.\n";
}
}
class Dog extends Animal {
public function bark() {
echo "$this->name is barking.\n";
}
}
$dog = new Dog();
$dog->name = "Buddy";
$dog->eat();
$dog->bark();
?>
Output
Buddy is eating.
Buddy is barking.
Types of Inheritance in PHP
1. Single Inheritance
PHP supports single inheritance, meaning a class can inherit from only one parent class at a
time.
<?php
class A {
public function sayHello() {
echo "Hello from A\n";
}
}
class B extends A {
public function sayHi() {
echo "Hi from B\n";
}
}
$objA = new A();
$objA->sayHello();
$objB = new B();
$objB->sayHello();
$objB->sayHi();
?>
Output
Hello from A
Hello from A
Hi from B
In this example:
Class A has a method sayHello(), which prints "Hello from A".
Class B extends class A, meaning it inherits the method sayHello(). It also defines its own
method sayHi() which prints "Hi from B".
An object $objA of class A is created, and calling sayHello() prints "Hello from A".
An object $objB of class B is created, which can access sayHello() from class A and
sayHi() from class B.
$objB demonstrates inheritance as it can use both the inherited method and its own
method.
This is an example of single inheritance, where class B inherits from class A.
2. Multilevel Inheritance
In multilevel inheritance, a class inherits from a class, which in turn inherits from another
class.
<?php
class A {
public function greet() {
echo "Hello from A\n";
}
}
class B extends A {
public function welcome() {
echo "Welcome from B\n";
}
}
class C extends B {
public function message() {
echo "Message from C\n";
}
}
$objA = new A();
$objA->greet();
$objB = new B();
$objB->greet();
$objB->welcome();
$objC = new C();
$objC->greet();
$objC->welcome();
$objC->message();
?>
Output
Hello from A
Hello from A
Welcome from B
Hello from A
Welcome from B
Message from C
In this example:
Defines a method greet(), which prints "Hello from A".
Inherits from class A and adds a new method welcome(), which prints "Welcome from
B".
Inherits from class B and adds another method message(), which prints "Message from
C".
$objA can only access greet().
$objB can access greet() from class A and welcome() from class B.
$objC can access methods from both A and B and also its own message() method.
This is multilevel inheritance, where class C inherits from B, and B inherits from A.
Constructor in Inheritance
If the parent class has a constructor, the child class must explicitly call it using
parent::__construct().
class Person {
public function __construct($name) {
echo "Person: $name\n";
}
}
class Student extends Person {
public function __construct($name, $rollNo) {
parent::__construct($name);
echo "Student Roll No: $rollNo\n";
}
}