0% found this document useful (0 votes)
23 views46 pages

PHP CH 03 52859676 2025 02 04 10 48

Object-Oriented Programming (OOP) is a programming paradigm centered around classes and objects, contrasting with procedural programming. Classes serve as blueprints for creating objects, which encapsulate both data and methods, allowing for code reusability and organization. Key concepts include constructors, destructors, access modifiers, and inheritance, which enhance the functionality and structure of programs.

Uploaded by

pranavugale31
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views46 pages

PHP CH 03 52859676 2025 02 04 10 48

Object-Oriented Programming (OOP) is a programming paradigm centered around classes and objects, contrasting with procedural programming. Classes serve as blueprints for creating objects, which encapsulate both data and methods, allowing for code reusability and organization. Key concepts include constructors, destructors, access modifiers, and inheritance, which enhance the functionality and structure of programs.

Uploaded by

pranavugale31
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

`

What is Object Oriented Programming?


Object-Oriented Programming (OOP) is a programming model that is based on the concept of classes
and objects. As opposed to procedural programming where the focus is on writing procedures or
functions that perform operations on the data, in object-oriented programming the focus is on the
creations of objects which contain both data and functions together.

Understanding Classes and Objects


Classes and objects are the two main aspects of object-oriented programming.
A class is a collection of variables and functions which work together to perform one or more specific
tasks, while objects are individual instances of a class.
A class acts as a template or blueprint from which lots of individual objects can be created. When
individual objects are created, they possesss the same generic properties and behaviors, although each
object may have different values for certain properties.
For example, think of a class as a blueprint for a house. The blueprint itself is not a house, but is a
detailed plan of the house. While, an object is like an actual house built according to that blueprint. We
can build several identical houses from the same blueprint, but each house may have different paints,
interiors and families inside, as shown in the illustration below.
`
Define a Class
Class − This is a user-defined data type.
It includes local functions as well as local data.
Class is a template or blueprint to create 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 are written inside the braces:

Syntax
<?php
class ClassName
{
//...
}
?>

Example:
Below we declare a class named Fruit consisting of two properties ($name and $color) and two
methods set_data() and get_data() for setting and getting the property:

class Fruit
{
public $name;
public $color;

function set_data($name,$color)
{
$this->name = $name;
$this->color = $color;
}
function get_data()
{
echo "Name of Fruit is ", $this->name,"<br>";
echo "Color of Fruit is ", $this->color;
}
}

Note: In a class, variables are called properties and functions are called methods!
`
Define 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.
Object of a class is created using the new keyword.

Example:
$apple = new Fruit();
$mango = new Fruit();

The object operator i.e. arrow symbol (->) is an OOP construct that is used to access properties and
methods for a given object.

$object->property;
$object->method( );

Example

<?php
class Fruit
{
public $name;
public $color;

function set_data($name,$color)
{
$this->name = $name;
$this->color = $color;
}

function get_data()
{
echo "Name of Fruit is ", $this->name,"<br>";
echo "Color of Fruit is ", $this->color;
}
}

$apple = new Fruit();


$apple->set_data('Apple','Red');
$apple->get_data();
?>
`
PHP - The $this Keyword

The $this keyword refers to the current object, and is only available inside methods.
The $this keyword allows you to access the properties and methods of the current object within
the class using the object operator (->):

$this->property
$this->method()

The $this keyword is only available within a class.

It doesn’t exist outside of the class. If you attempt to use the $this outside of a class, you’ll get an
error.

When you access an object property using the $this keyword, you use the $ with the this keyword only.
And you don’t use the $ with the property name.

Example
<?php
class Fruit {
public $name;
public $color;

function set_data($name,$color)
{
$this->name = $name;
$this->color = $color;
}

function get_data()
{
echo "Name of Fruit is ", $this->name,"<br>";
echo "Color of Fruit is ", $this->color;
}
}

$apple = new Fruit();


$apple->set_data('Apple','Red');
$apple->get_data();
?>

Output:
Name of Fruit is Apple
Color of Fruit is Red
`
 Change the property value directly Outside the class:
Example
<?php
class Fruit
{
public $name;
public $color;

function get_data()
{
echo "Name of Fruit is ", $this->name,"<br>";
echo "Color of Fruit is ", $this->color;
}
}

$obj = new Fruit();


$obj->name = 'Apple';
$obj->color= 'Red';
$obj->get_data();
?>
`
Program: Calculate Perimeter and Area of Rectangle
<?php
class Rectangle {
public $length;
public $breadth;
public $p;
public $a;

function get_data($length,$breadth)
{
$this->length=$length;
$this->breadth=$breadth;
}

function perimeter()
{
$this->p= 2*($this->length + $this->breadth);
echo "Perimeter is ", $this->p,"<br>";
}

function area()
{
$this-> a = $this->length * $this->breadth;
echo "Area is ", $this->a;
}
}

$Rect1 = new Rectangle();


$Rect1->get_data(10,20);
$Rect1->perimeter();
$Rect1->area();
?>

Output:-
Perimeter is 60
Area is 200
`
Program : Calculate Area and Circumference of Circle
<?php
class Circle
{
public $radius;

function set_data($radius)
{
$this->radius=$radius;
}

function area()
{
echo "Area of circle is ". (3.14 * $this->radius*$this->radius)."<br>";
}

function circumference()
{
echo "circumference of Circle is ".(2*3.14*$this->radius);
}

}
$obj = new Circle();
$obj->set_data(5);
$obj->area();
$obj->circumference();

?>

Program : Returning Values from Function

<?php
class Circle
{
public $radius;

function set_data($radius)
{
$this->radius=$radius;
}

function area()
{
$a = 3.14*$this->radius*$this->radius; // $a does not require this keyword
`
return $a;
}

function circumference()
{
$c = 2*3.14*$this->radius;
return $c;
}

}
$obj = new Circle();
$obj->set_data(10);
echo "Area of Circle is ",$obj->area();
echo "Circumference of Circle is ",$obj->circumference();

?>

PHP - instanceof
You can use the instanceof keyword to check if an object belongs to a specific class:
Example:-
var_dump($apple instanceof Fruit);

Constructor
The __construct Function
Constructor are special type of functions which are called automatically whenever an object is
created.
A constructor allows you to initialize an object's properties upon creation of the object.
PHP provides a special function called __construct() to define a constructor.
You can pass as many as arguments you like into the constructor function.

Notice that the construct function starts with two underscores (_ _)!

class ClassName
{
function __construct()
{
// implementation
}
}

When you create an instance of the class, PHP automatically calls the constructor method:

$object = new ClassName()


`
Example:-
<?php
class Fruit
{
function __construct()
{
echo "Constructor Is Invoked";
}
}
$obj = new Fruit(); //constructor invoked
?>

Example
<?php
class Fruit

{
public $name;
function __construct($name)

{
$this->name = $name;
}
function get_name()

{
return $this->name;
}
}

$apple = new Fruit("Apple");


echo $apple->get_name();
?>

Example
<?php
class Fruit {
public $name;
public $color;

function __construct($name, $color)

{
$this->name = $name;
`
$this->color = $color;
}
function get_name()

{
return $this->name;
}
function get_color()

{
return $this->color;
}
}
$apple = new Fruit("Apple", "red");
echo $apple->get_name();
echo "<br>";
echo $apple->get_color();
?>

Destructor
The __destruct Function
A destructor is called when the object is destructed or the script is stopped or exited.
If you create a __destruct() function, PHP will automatically call this function at the end of the script.
Notice that the destruct function starts with two underscores (_ _)!

function __destruct()

// destroying the object or clean up resources here

Example
<?php
class Fruit
{
public $name;
public $color;
function __construct($name,$color)
{
$this->name= $name;
$this->color= $color;
}
`
function get_name()
{
echo "Name of Fruit is ". $this->name."<br>";
}

function get_color()
{
echo "Color of Fruit is ".$this->color."<br>";
}

function __destruct()
{
echo "Object is Destroyed";
}

$obj = new Fruit("Apple","Red"); //constructor invoked


$obj->get_name();
$obj->get_color();

?>

2) Parameterized Constructor

A constructor can be with or without arguments. The constructor with arguments is called the
parameterized constructor

<?php
class Person
{
public $first;
public $email;
public $mobile;

function __construct($name, $email, $mobile)


{
echo "Initialising the object...<br/>";
$this->name = $name;
$this->email = $email;
$this->mobile = $mobile;
}
function display()
{
`
echo "My name is: " . $this->name. "<br>";
echo "Email_Id is ".$this->email. "<br>";
echo "Mobile Number is ". $this->mobile."<br>";
}
}
$P1 = new Person("Akshay","[email protected]", "8788335443");
$P1->display();
?>

Output:
Initialising the object...
My name is: Akshay
Email_Id is [email protected]
Mobile Number is 8788335443

PHP - Access Modifiers


Properties and methods can have access modifiers which control where they can be accessed.

There are three access modifiers:

 public - the property or method can be accessed from everywhere. This is default.
 protected - the property or method can be accessed within the class and by classes derived
from that class
 private - the property or method can ONLY be accessed within the class

In the following example we have added three different access modifiers to the three properties. Here,
if you try to set the name property it will work fine (because the name property is public). However, if
you try to set the color or weight property it will result in a fatal error (because the color and weight
property are protected and private):

Example
<?php
class Fruit

{
public $name;
protected $color;
private $weight;
}

$mango = new Fruit();


$mango->name = 'Mango'; // OK
`
$mango->color = 'Yellow'; // ERROR
$mango->weight = '300'; // ERROR
?>

In the next example we have added access modifiers to two methods. Here, if you try to call the
set_color() or the set_weight() function it will result in a fatal error (because the two functions are
considered protected and private), even if all the properties are public:

Example
<?php
class Fruit

{
public $name;
public $color;
public $weight;
function set_name($n)

{ // a public function (default)


$this->name = $n;
}
protected function set_color($n)

{ // a protected function
$this->color = $n;
}
private function set_weight($n)

{ // a private function
$this->weight = $n;
}
}

$mango = new Fruit();


$mango->set_name('Mango'); // OK
$mango->set_color('Yellow'); // ERROR
$mango->set_weight('300'); // ERROR
?>

Output
Fatal error: Uncaught Error: Call to protected method Fruit::set_color() from global scope in
C:\xampp\htdocs\PHP_PROGRAM\access.php:20 Stack trace: #0 {main} thrown
in C:\xampp\htdocs\PHP_PROGRAM\access.php on line 20
`
PHP - What is Inheritance?
Inheritance is the way of extending the existing class functionality in the newly created class.
We can also add some additional functionality to the newly created class apart from extending the base
class functionalities.
When we inherit one class, we say an inherited class is a child class (sub class) and from which we
inherit is called the parent class. The parent class is also known as the base class.
This is the way that enables the better management of the programming code and code reusability.
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.

class derived_class_name extends base_class_name


{
// define member functions of the derived class here.
}

Single Inheritance: PHP supports Single inheritance. Single inheritance is a concept in PHP in which
one class can be inherited by a single class only. We need to have two classes in between this process.
One is the base class (parent class), and the other a child class itself.

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.

Examples :- Single Inheritance


<?php
class demo
{
function display()
{
echo "Example of inheritance ";
}
}
class demo1 extends demo
{
function view()
{
echo "in php";
}
}
$obj= new demo1();
$obj->display();
$obj->view();
?>
`
Example : 2
<?php
class Fruit
{
public $name;
public $color;
function set($name, $color)
{
$this->name = $name;
$this->color = $color;
}
function display( )
{
echo "The fruit is ". $this->name."<br>";
echo "the color is ". $this->color;
}
}
class Apple extends Fruit
{
function message()
{
echo "Am I a fruit "."<br>";
}
}
$s = new Apple();
$s->set("Apple", "Red");
$s->message();
$s->display();
?>

Output:-
Am I a fruit
The fruit is Apple
the color is Red

Example: Using Constructor in Base Class


<?php
class Fruit
{
public $name;
public $color;
function __construct($name, $color)
{
$this->name = $name;
$this->color = $color;
}
function display( )
{
echo "The fruit is ". $this->name."<br>";
echo "the color is ". $this->color;
`
}
}
class Apple extends Fruit
{
function message()
{
echo "Am I a fruit "."<br>";
}
}
$s = new Apple("Apple", "Red");
$s->message();
$s->display();
?>

Inheritance and the Protected Access Modifier


protected properties or methods can be accessed within the class and by classes derived from that
class.

Example
<?php
class Fruit
{
public $name;
public $color;
public function __construct($name, $color)
{
$this->name = $name;
$this->color = $color;
}
protected function display()
{
echo "The fruit is ". $this->name."<br>";
echo "the color is ". $this->color;
}
}
class Apple extends Fruit
{
function message()
{
echo "Am I a fruit "."<br>";
}
}
$s = new Apple("Apple", "Red"); // OK. __construct() is public
$s->message();// OK. message() is public
$s->display(); // ERROR. display() is protected
?>
`
In the example above we see that if we try to call a protected method (display()) from outside the class,
we will receive an error. public methods will work fine!

Let's look at another example: Here we will call the protected method (display ()) from inside the
derived class.

Example
<?php
class Fruit
{
public $name;
public $color;
public function __construct($name, $color)
{
$this->name = $name;
$this->color = $color;
}
protected function display()
{
echo "The fruit is ". $this->name."<br>";
echo "the color is ". $this->color;
}
}
class Apple extends Fruit
{
function message()
{
echo "Am I a fruit "."<br>";
$this->display();
}
}
$s = new Apple("Apple", "Red"); // OK. __construct() is public
$s->message(); // OK. message() is public and it calls intro() (which is protected) from within the
derived class
?>

Output:-
Am I a fruit
The fruit is Apple
the color is Red
`
Multi-level inheritance
Example:-
<?php
//PHP program to demonstrate the multi-level inheritance.
class Base
{
function BaseFun()
{
echo "BaseFun() called <br>";
}
}

class Derived1 extends Base


{
function Derived1Fun()
{
echo "Derived1Fun() called<br>";
}
}

class Derived2 extends Derived1


{
function Derived2Fun()
{
echo "Derived2Fun() called<br>";
}
}

$Obj = new Derived2();


$Obj->BaseFun();
$Obj->Derived1Fun();
$Obj->Derived2Fun();

?>

Hierarchical inheritance
<?php
//PHP program to demonstrate the hierarchical inheritance.
class Base
{
function BaseFun()
{
echo "BaseFun() called<br>";
}
}
`
class Derived1 extends Base
{
function Derived1Fun()
{
echo "Derived1Fun() called<br>";
}
}

class Derived2 extends Base


{
function Derived2Fun()
{
echo "Derived2Fun() called<br>";
}
}

$Obj1 = new Derived1();


$Obj2 = new Derived2();

$Obj1->BaseFun();
$Obj1->Derived1Fun();

echo "<br>";

$Obj2->BaseFun();
$Obj2->Derived2Fun();

?>

Multiple Inheritance
Multiple Inheritance is the property of the Object Oriented Programming languages in which child
class or sub class can inherit the properties of the multiple parent classes or super classes.
PHP doesn’t support multiple inheritance but by using Interfaces in PHP or using trait in PHP
instead of classes, we can implement it.
Traits are used to declare methods that can be used in multiple classes. Traits can have methods and
abstract methods that can be used in multiple classes, and the methods can have any access modifier
(public, private, or protected).
Traits are declared with the trait keyword:
Syntax

<?php
trait TraitName
{
// some code...
}
?>
`
To use a trait in a class, use the use keyword:

Syntax
<?php
class child_class extends parent_class
{
use trait_name;
..
..
Child_class function/functions
}
?>

Example:-
<?php
class A // Parent Class
{
function display1()
{
echo "Hello ";
}
}

trait B // Trait
{
function display2()
{
`
echo "Welcome ";
}
}

class C extends A //Derived Class


{
use B;

function display3()
{
echo "Arrow Academy ";
}
}

$obj = new C();


$obj->display1();
$obj->display2();
$obj->display3();
?>

Interfaces
 An interface consists of methods that have no implementations, which means the interface
methods are abstract methods.
 Any classes implementing an interface must implement all methods defined by the
interface.
 All the methods in interfaces must have public visibility scope.
 Interfaces are different from classes as the class can inherit from one class only whereas the
class can implement one or more interfaces
 A class can implement multiple interfaces.
 An interface is declared using the "interface" keyword.

Interface (Using Class along with Interface):


Syntax:

class child_class_name extends parent_class_name implements interface_name1, …..


{

// defines the interface methods and may have its own code
}
`
Example:-
<?php
class A // Parent Class
{
function display1()
{
echo "You are in Class A <br>";
}
}

interface B // Interface Declared


{
function display2(); // Abstract Method
}

class C extends A implements B


{
function display2()
{
echo "You are in Interface B <br>";
}

function display3()
{
echo "You are in Class C ";
}
}

$obj = new C();


$obj->display1();
$obj->display2();
$obj->display3();
?>
Output:-
You are in Class A
You are in Interface B
You are in Class C
`
Example:- Class implementing multiple Interfaces
<?php
class A
{
public function display1()
{
echo "You are in class A <br>";
}
}
interface B
{
public function display2();
}

interface C
{
public function display3();
}

class Multiple extends A implements B,C


{
function display2()
{
echo "You are in the interface B <br>";
}
public function display3()
{
echo "You are in the interface C <br>";
}
public function display4()
{
echo "You are in the Class Multiple <br>";
}

$obj = new multiple();


$obj->display1();
$obj->display2();
$obj->display3();
$obj->display4();
?>
`
Abstract class

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.
An abstract class or method is defined with the abstract keyword.
Classes defined as abstract cannot be instantiated.
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration
must be defined by the child class

Syntax:-
abstract class class_name
{
abstract public function method_name( $param1, $param2 );
}

Example:-

<?php

// Abstract class
abstract class Base
{
// This is abstract function
abstract function printdata();
}
class Derived extends Base
{
function printdata()
{
echo "Derived class";
}
}
$b1 = new Derived;
$b1->printdata();
?>
`
Concrete Class:
The class which implements an interface is called the Concrete Class.
It must implement all the methods defined in an interface.

<?php

interface MyInterfaceName
{

public function method1();


public function method2();

class MyClassName implements MyInterfaceName{

public function method1()


{
echo "Method1 Called" . "\n";
}

public function method2()


{
echo "Method2 Called". "\n";
}
}

$obj = new MyClassName;


$obj->method1();
$obj->method2();

?>
Output:
Method1 Called
Method2 Called
`
Property Overloading
PHP property overloading is used to create dynamic properties when the object is set.
For creating these properties no separate line of code is needed.
A property associated with a class instance, and if it is not declared within the scope of the class, it is
considered as overloaded property.
To achieve this we can use the magic method
 __set(): triggered while initializing overloaded properties.
 __get(): triggered while using overloaded properties with PHP print statements.
 __isset(): This magic method is invoked when we check overloaded properties with isset() function
 __unset(): Similarly, this function will be invoked on using PHP unset() for overloaded properties.
Program:-
<?php
class myclass
{
function __set($name,$value)
{
echo "Setting $name propert with $value <br>";
$this->$name=$value;
}
function __get($name)
{
return $this->name;
}

function __isset($name)
{
return isset($this->name);
}
function __unset($name)
{
unset($this->name);
}
}
$obj = new myclass();
$obj->myprop="test"; // Invoke set()
echo "Value of overloaded Property is ";
echo $obj->myprop; // Invoke get()
echo "<br>";
var_dump (isset($obj->myprop));
unset($obj->myprop);
echo "<br>";
var_dump(isset($obj->myprop));

?>Output:-
Setting myprop propert with test
Value of overloaded Property is test
bool(true)
bool(false)
`
Function Overloading:
Function overloading contains same function name and that function performs different task
according to number of arguments. For example, find the area of certain shapes where radius are given
then it should return area of circle, if height and width are given then it should give area of rectangle
and others. Like other OOP languages function overloading can not be done by native approach. In PHP
function overloading is done with the help of magic function __call(). This function takes function name
and arguments.
Syntax:
public __call (string $name1 , array $arguments1 )
Example:-
<?php
// PHP program to explain function
// overloading in PHP

// Creating a class of type shape


class shape {

// __call is magic function which accepts


// function name and arguments
function __call($name, $arguments) {

// It will match the function name


if($name == 'area') {

switch (count($arguments)) {

// If there is only one argument area of circle


case 1:
return 3.14 * $arguments[0]* $arguments[0];

// IF two arguments then area of rectangle;


case 2:
return $arguments[0]*$arguments[1];
}
}
}
}

// Declaring a shape type object


$circle = new Shape();
$rect = new Shape();
// // calling area method for circle
echo "Area of Circle is ".($circle->area(2));
echo "<br>";

// calling area method for rectangle


echo "Area of Rectangle is ".($rect->area(4, 2));
?>
`
Example 2:-
<?php

class Calculate
{
function __call($name, $arguments)
{

if($name == 'add')
{

switch (count($arguments))
{

case 1:
return $arguments[0];

case 2:
return $arguments[0] + $arguments[1];

case 3:
return $arguments[0] + $arguments[1] + $arguments[2];

case 4:
return $arguments[0] + $arguments[1] + $arguments[2] + $arguments[3];

}
}
}
}

$C1 = new Calculate();


echo "Addition is ".($C1->add(4,2))."<br>";
echo "Addition is ".($C1->add(5,2,3))."<br>";
echo "Addition is ".($C1->add(4,4,5,5))."<br>";
?>
`
PHP - Overriding Inherited Methods
In function overriding, both parent and child classes have same function name with and number of
arguments.
It is used to replace parent method in child class.
The purpose of overriding is to change the behavior of parent class method.
Inherited methods can be overridden by redefining the methods (use the same name) in the child
class.
Example:- Overiding display() function of Base class
<?php
class Base {
function display() {
echo "Base class function ";
}

}
class Derived extends Base {
function display() {
echo " Derived class function!";
}
}
$ob = new Derived;
$ob->display();
?>

Example 2:
Look at the example below. The __construct() and intro() methods in the child class (Strawberry) will
override the __construct() and intro() methods in the parent class (Fruit):
<?php

class Fruit

{
public $name;
public $color;

function __construct($name,$color)
{
$this->name= $name;
$this->color = $color;
}

function display()
{
echo "Name is ".$this->name;
echo "Color is ".$this->color;
}
`
}

class Apple extends Fruit


{
public $weight;

function __construct($name,$color,$weight)
{
$this->name= $name;
$this->color = $color;
$this->weight = $weight;
}

function display()
{
echo "Name is ".$this->name."<br>";
echo "Color is ".$this->color."<br>";
echo "Weight is ".$this->weight."<br>";
}
}

$obj = new Apple("Apple","Red","100");


$obj->display();

?>

Output:

Name is Apple
Color is Red
Weight is 100
`
final Keyword
The final keyword can be used to prevent class inheritance or to prevent method overriding.
When a class is declared as Final , it can not be Inherited.
When a method is declared as Final , then overriding can not be performed on that method..

The following example shows how to prevent class inheritance:


<?php
final class Base {
function display() {
echo "Base class function ";
}
}
class Derived extends Base {
function display() {
echo " Derived class function!";
}
}
$ob = new Derived;
$ob->display();
?>

Output:-
Fatal error: Class Derived may not inherit from final class (Base)
in C:\xampp\htdocs\Practicals\Demo.php on line 11

The following example shows how to prevent method overriding:

<?php
class Base {
final function display() {
echo "Base class function ";
}

}
class Derived extends Base {
function display() {
echo " Derived class function!";
}
}
$ob = new Derived;
$ob->display();
?>
`
Output:-

Fatal error: Cannot override final method Base::display()


in C:\xampp\htdocs\Practicals\Demo.php on line 9

PHP Object Cloning


Introduction
Object cloning is creating a copy of an object.
When copy of an object is created by simple assignment, then it only creates another reference to the
original object in memory.
Hence, changes in attribute reflect both in original and duplicate object.
PHP has clone keyword that creates a shallow copy of the object.
However, if original object has other embedded object as one of its properties, the copied object still
refers to the same.
To create a deep copy of object, the magic method __clone() needs to be defined in the class.

Copy Objects by Assignment


In following code, myclass has two attributes name and city.
An object of myclass is duplicated by assignment.
Change in value of its prroperty is reflected in both objects
So, this type of copy is just a duplicate reference to the original instance.
Technically this is not a copy, but it is just assigning the object’s reference to another object.

Example:-
<?php
class myclass
{
public $name;
public $city;
function __construct($name,$city)
{
$this->name= $name;
$this->city=$city;
}
}

$obj1 = new myclass("Arrow","Ahmednagar");


echo "Original Object <br>";
print_r($obj1);
echo "<br>";
$obj2 = $obj1;
echo "Duplicate Object ";
echo "<br>";
print_r($obj2);

$obj2->name= "Akshay";
`
$obj2->city= "Pune";

echo "<br>";
echo "After Changing Properties <br>";
echo "Original Object <br>";
print_r($obj1);
echo "<br>";

echo "Duplicate Object ";


echo "<br>";
print_r($obj2);

?>

Output:-
Original Object
myclass Object ( [name] => Arrow [city] => Ahmednagar )
Duplicate Object
myclass Object ( [name] => Arrow [city] => Ahmednagar )
After Changing Properties
Original Object
myclass Object ( [name] => Akshay [city] => Pune )
Duplicate Object
myclass Object ( [name] => Akshay [city] => Pune )

Object Copy by clone keyword


In the below example, we are copying objects by using PHP clone keyword
The clone keyword creates a shallow copy.
Change in value of property doesn't reflect in cloned object.

<?php
class myclass
{
public $name;
public $city;
function __construct($name,$city)
{
$this->name= $name;
$this->city=$city;
}
}

$obj1 = new myclass("Arrow","Ahmednagar");


echo "Original Object <br>";
print_r($obj1);
`
echo "<br>";

$obj2 =clone $obj1; // Use of Clone keyword, creates sghallow copy


echo "Duplicate Object ";
echo "<br>";
print_r($obj2);

$obj2->name= "Akshay";
$obj2->city= "Pune";

echo "<br>";
echo "After Changing Properties <br>";
echo "Original Object <br>";
print_r($obj1);
echo "<br>";

echo "Duplicate Object ";


echo "<br>";
print_r($obj2);

?>

Output:
Original Object
myclass Object ( [name] => Arrow [city] => Ahmednagar )
Duplicate Object
myclass Object ( [name] => Arrow [city] => Ahmednagar )
After Changing Properties
Original Object
myclass Object ( [name] => Arrow [city] => Ahmednagar )
Duplicate Object
myclass Object ( [name] => Akshay [city] => Pune )
`
Shallow Copy vs Deep Copy
Shallow Copy
As mentioned ealier, the clone performs a shallow copy of an object. It means that:
1. Create a copy of all properties of an object.
2. If a property references another object, the property remains a reference.
In other words, when an object has a property that references another object, that property remains a
reference after cloning.

<?php
class address
{
public $city = "Nanded";
public $pin = "123456";
function setaddr($city,$pin)
{
$this->city= $city;
$this->pin=$pin;
}
}

class myclass
{
public $name = "Raja";
public $obj;

function setname($name)
{
$this->name= $name;
}
}

$obj1= new myclass();


$obj1->obj=new address();

echo "Original Object <br>";


print_r ($obj1);

$obj2=clone $obj1;

echo "Duplicate Object <br>";


print_r ($obj2);

$obj2->setname("Akshay");
`
$obj2->obj->setaddr("Nagar","414001");

echo "<br>";
echo "Original Object <br>";
print_r ($obj1);
echo "<br>";
echo "Duplicate Object <br>";
print_r ($obj2);

?>
Output:-
Original Object
myclass Object ( [name] => Raja [obj] => address Object ( [city] => Nanded [pin] => 123456 ) )
Duplicate Object
myclass Object ( [name] => Raja [obj] => address Object ( [city] => Nanded [pin] => 123456 ) )
Original Object
myclass Object ( [name] => Raja [obj] => address Object ( [city] => Nagar [pin] => 414001 ) )
Duplicate Object
myclass Object ( [name] => Akshay [obj] => address Object ( [city] => Nagar [pin] => 414001 ) )
`
Deep copy with __clone method
Deep copy creates a copy of an object and recursively creates a copy of the objects referenced by the
properties of the object.
The __clone() method creates a deep copy by creating clone of embedded object too.

Example:-

<?php
class address
{
public $city = "Nanded";
public $pin = "123456";
function setaddr($city,$pin)
{
$this->city= $city;
$this->pin=$pin;
}
}
class myclass
{
public $name = "Raja";
public $obj;

function setname($name)
{
$this->name= $name;
}

function __clone()
{
$this->obj= clone $this->obj;
}
}

$obj1= new myclass();


$obj1->obj=new address();

echo "Original Object <br>";


print_r ($obj1);

$obj2=clone $obj1;

echo "Duplicate Object <br>";


`
print_r ($obj2);

$obj2->setname("Akshay");
$obj2->obj->setaddr("Nagar","414001");

echo "<br>";
echo "Original Object <br>";
print_r ($obj1);
echo "<br>";
echo "Duplicate Object <br>";
print_r ($obj2);
?>

Output:-

Original Object
myclass Object ( [name] => Raja [obj] => address Object ( [city] => Nanded [pin] => 123456 ) )
Duplicate Object
myclass Object ( [name] => Raja [obj] => address Object ( [city] => Nanded [pin] => 123456 ) )
Original Object
myclass Object ( [name] => Raja [obj] => address Object ( [city] => Nanded [pin] => 123456 ) )
Duplicate Object
myclass Object ( [name] => Akshay [obj] => address Object ( [city] => Nagar [pin] => 414001 ) )
`
Introspection in PHP:
Introspection is the ability of a program to examine an object's characteristics, such as its name, parent
class (if any), properties, and methods.
PHP offers a large number of functions that you can use to accomplish the task.
The following are the functions to extract basic information about classes such as their name, the name
of their parent class and so on.
In-built functions in PHP Introspection :

Function Description
class_exists() Checks whether a class has been defined.
get_class() Returns the class name of an object.
get_parent_class() Returns the class name of object's parent class.
is_subclass_of() Checks whether an object has a given parent class.
get_declared_classes() Returns a list of all declared classes.
get_class_methods() Returns the names of the class methods.
get_class_vars() Returns the default properties of a class
interface_exists() Checks whether the interface is defined.
method_exists() Checks whether an object defines a method.

To determine whether a class exists, use the class_exists( ) function, which takes in a string and
returns a Boolean value.
Example 1: class_exists( )

<?php
if(class_exists('arrow'))
{
$ob=new arrow();
echo "This is Arrow Computer";
}
else
{
echo "Not exist";
}
?>
Output: Not exist
`
Example 2: class_exists( )
<?php
class arrow
{
//Body
}
if(class_exists('arrow'))
{
$ob=new arrow();
echo "This is Arrow";
}
else
{
echo "Not exist";
}
?>
Output: This is Arrow
`
The get_class() and get_parent_class() methods return the class name of an object or its parent’s
class name respectively. Both takes as arguments an object instance.
The is_subclass_of() methods takes an object instance as its first argument and a string, representing
the parent class name, Checks whether an object has a given parent class.

Example 3:
<?php
class A
{
public function description()
{
echo "I am a super class for the Child class <br>";
}
}
class B extends A
{
public function description()
{
echo "I am Class " .get_class($this)."<br>";
echo "I am Child Class of " .get_parent_class($this)."<br>";
}
}
if (class_exists('A'))
{
$base = new A();
echo "The class name is: " . get_class($base)."<br>";
$base->description();
}

if (class_exists('B'))
{
$child = new B();
$child->description();
if (is_subclass_of($child,'A'))
{
echo "Yes, " . get_class($child) . " is a subclass of A";
}
else
{
echo "No, " . get_class($child) . " is not a subclass of A";
}
}
`
The output of the above code should be as follows:

The class name is: A


I am a super class for the Child class
I am Class B
I am Child Class of A
Yes, B is a subclass of A

Example 4: Declare a class Test with three User Defined Function.


List name of functions declared in class Test
<?php
class Test
{
function display1()
{
echo "Dipslay 1";
}
function display2()
{
echo "Dipslay 2";
}
function display3()
{
echo "Dipslay 3";
}
}
if(class_exists('Test'))
{
echo "Class Test Exists <br>";
$t = new Test();
}
else
{
echo "Class Test Does Not Exists";
}
echo "Name of Class is ".get_class($t)."<br>";
$methods = get_class_methods('Test');
echo "List of Methods: <br>";
foreach ($methods as $name)
{
echo "$name <br>";
}
`
Output:-

Class Test Exists


Name of Class is Test
List of Methods:
display1
display2
display3

Example 5:- Based on Interface Exists


<?php
interface Test
{
function display();
}

class MyClass implements Test


{
function display()
{
echo "Dipslay method From Interface Test";
}
}

if(interface_exists('Test'))
{
echo "Interface Test Exists <br>";
}
else
{
echo "Interface Test Does Not Exists";
}
$t = new Myclass();
$t->display1();

Output:-
Interface Test Exists
Dipslay 1 method From Interface Test

You can get the methods and properties that exist in a class (including those that are inherited from
superclasses) using the get_class_methods( ) and get_class_vars( ) functions. These functions take a
class name and return an array:
`
Example 6:
<?php
class Rectangle
{
var $length = 2;
var $breadth = 10;
function get($length,$breadth)
{
$this->length = $length;
$this->breadth = $breadth;
}

function area()
{
return $this->length*$this->breadth;
}
function display()
{
// any code to display info
}
}
$S = new Rectangle();
$S->get(4,2);
//get the class varibale i.e properties
$class_properties = get_class_vars('Rectangle');

//get class methods


$class_methods = get_class_methods('Rectangle');

//get class corresponding to an object


$object_class = get_class($S);

print_r($class_properties);
echo "<br>";
print_r($class_methods);
echo "<br>";
print_r($object_class);
?>

Output:
Array ( [length] => 2 [breadth] => 10 )
Array ( [0] => Rectangle [1] => area [2] => display )
Rectangle
`
1. Serialize
The serialize() is an inbuilt function PHP that is used to serialize the given array.
The serialize() function converts a storable representation of a value.
To serialize data means to convert a value to a sequence of bits, so that it can be stored in a file, a
memory buffer, or transmitted across a network.
The serialize() function accepts a single parameter which is the data we want to serialize and returns a
serialized string.
Syntax

serialize($values_in_form_of_array);
Example 1:

<?php

// Complex array
$arr = array("Red", "Green", "Blue");

// Serialize the above data


$string = serialize($arr);

// Printing the unserialized data


print_r($string);

?>
Output:
a:3:{i:0;s:3:"Red";i:1;s:5:"Green";i:2;s:4:"Blue";}

Example 2:
<?php
class test1
{
private $name;
function __construct($arg)
{
$this->name=$arg;
}
}
$obj1=new test1("Akshay");
$str=serialize($obj1);
echo $str
?>
Output:

O:5:"test1":1:{s:11:"test1name";s:5:" Akshay ";}


`
2. PHP unserialize() Function

The unserialize() function converts serialized data back into actual data.
Syntax:-
Unserialize( $serialized_array )
Example
Convert serialized data back into actual data:
<?php
$arr = array("Red", "Green", "Blue");
$data = serialize($arr);
echo $data . "<br>";
$test = unserialize($data);
var_dump($test);
?>
Output:

a:3:{i:0;s:3:"Red";i:1;s:5:"Green";i:2;s:4:"Blue";}
array(3) { [0]=> string(3) "Red" [1]=> string(5) "Green" [2]=> string(4) "Blue" }

You might also like