0% found this document useful (0 votes)
19 views39 pages

Unit -3 Apply Object Oriented Concepts in PHP

This document provides an overview of object-oriented concepts in PHP, including the creation of classes and objects, constructors and destructors, inheritance, method overloading and overriding, cloning, introspection, and serialization. It includes syntax examples and explanations for each concept, demonstrating how to implement them in PHP. The document serves as a guide for understanding and applying these object-oriented programming principles in PHP development.

Uploaded by

viki06sk
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)
19 views39 pages

Unit -3 Apply Object Oriented Concepts in PHP

This document provides an overview of object-oriented concepts in PHP, including the creation of classes and objects, constructors and destructors, inheritance, method overloading and overriding, cloning, introspection, and serialization. It includes syntax examples and explanations for each concept, demonstrating how to implement them in PHP. The document serves as a guide for understanding and applying these object-oriented programming principles in PHP development.

Uploaded by

viki06sk
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
You are on page 1/ 39

Unit -3

Apply Object Oriented Concepts in


PHP

Mrs.Alinka sachin shinde


Lecturer in information technology
p.l.govt.polytechniclatur
Class and Object
 Write syntax to create class and object in PHP
 A class is defined by using the class keyword, followed by the name of
the class and a pair of curly braces ({}).
 A set of braces enclosing any number of variable declarations and
function definitions.
 In a class, variables are called properties and functions are called
methods!
Syntax:
<?php
class person
{
// code goes here...
}
?>
Example
 Declare a class named Student consisting of two properties ($name and $class) and two
methods set_name() and get_name() for setting and getting the $name property:
 <?php
class Student
{
// Properties
public $name;
public $class;
// Methods
function set_name($name)
{
$this->name = $name;
}
function get_name()
{
return $this->name;
}
}
?>
Object
 An object is an instance of class.
 The data associated with an object are called its properties.
 The functions associated with an object are called its methods.
 Object of a class is created by using the new keyword followed by classname.
 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 = new Classname( );
 Example:
$Obj=new Student(); or $Obj=new Student;
<?php
class Student
{
// Properties
public $name;
public $class;
// Methods
function set_name($name)
{
$this->name = $name;
}
function get_name()
{
return $this->name;
}
}
$obj= new Student();
$obj->set_name(‘Sonam');
echo $obj->get_name();
?>
Constructor and Destructor
 When we create an object of any class, we need to set properties of that
object before using it. We can do that by first initializing the object and
then setting values for the properties.
 To create and initialize a class object in a single step, PHP provides a
special method called as Constructor, which is used to construct the object
by assigning the required property values while creating the object.
 Once the object is initialized, the constructor is automatically called.
 The main purpose of this method is to initialize the object.
 Destructors are for destroying objects and automatically called at the end
of execution.
 PHP Destructor method is called and is about to release any object from its
memory. Generally, you can close files, clean up resources etc in the
destructor method.
 In PHP, we have special functions to define constructor and destructor for a
class, they are: __construct() and __destruct().
<?php
class <CLASS_NAME> {
// constructor
function __construct()
{
// initialize the object properties
}

// destructor
function __destruct()
{
// clearing the object reference
}
}
?>

Constructor can accept arguments, whereas destructors won't have any


argument because a destructor's job is to destroy the current object reference.
<?php
class Person
{
private $fname;
private $lname;
public function __construct($fname, $lname)
{
echo "Initialising the object...<br/>";
$this->fname = $fname;
$this->lname = $lname;
}
public function __destruct()
{
echo "Destroying Object...";
}
public function show()
{
echo "My name is: " . $this->fname . " " . $this->lname . "<br/>";
}
}
$x = new Person(“Ram", “Reddy");
$x->show(); Output:
?> My name is: Ram Reddy
Destroying Object...
Inheritance
 Inheritance is a fundamental idea in object-oriented programming.
 Inheritance in OOP = When a class derives from another class.
 Inheritance is process by which a child class can inherit all the properties and characteristics of the
parent class.
 Inheritance enables a class to use properties and methods of an existing class.
 The class which is inherited is called Parent class(or super class or base class) while the class which is
inheriting other class is called as Child class(or sub class or derived 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.
 In PHP, extends keyword is used to define the child class.
 Inheritance allows a class to reuse the code from another class without duplicating it.
 Reusing existing codes serves various advantages. It saves time, cost, effort, and increases a
program’s reliability
 Syntax:
class derived_class_name extends base_class_name
{
// define member functions of
// the derived class here.
}
Example
<?php
class demo
{
public function display()
{
echo “Example of inheritance ";
}
}
class demo1 extends demo
{
public function view()
{
echo "in php";
}
}
$obj= new demo1();
$obj->display();
$obj->view(); Output:
?> Example of inheritance in php
Create a class as “Percentage” with two properties length & width. Calculate area of
rectangle for two objects.
Types of inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance(Interfaces)
4. Hierarchical Inheritance

Single Inheritance
In a single inheritance, there is only one base class and one sub or derived class. It
directly inherits the subclass from the base class.
<?php
//PHP program to demonstrate the single inheritance.
class Base
{
function BaseFun()
{
echo "BaseFun() called<br>";
}
}
class Derived extends Base
{
function DerivedFun()
{
echo "DerivedFun() called<br>";
}
}
$dObj = new Derived();
$dObj->BaseFun();
$dObj->DerivedFun();
?>
Output
BaseFun() called
DerivedFun() called
Multi-Level Inheritance
In the multi-level inheritance, we will inherit the one base class into a derived class, and
then the derived class will become the base class for another derived class. <?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>";
}
}
$dObj = new Derived2();
$dObj->BaseFun();
$dObj->Derived1Fun();
$dObj->Derived2Fun();
?>

Output
BaseFun() called
Derived1Fun() called
Derived2Fun() called
Hierarchical Inheritance
 In the hierarchical inheritance, we will inherit the one base class into multiple
derived classes.
<?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();
Output
BaseFun() called
?> Derived1Fun() called

BaseFun() called
Derived2Fun() called
Multiple Inheritance(Using interface)
 Multiple inheritance is a type of inheritance in which one class can inherit the
properties from more than one parent class.
 PHP doesn’t support multiple inheritance but by using Interfaces in PHP ,we can
implement it.

<?php
//PHP program to implement multiple-inheritance using the
interface.
class Base
{
public function Fun1()
{
printf("Fun1() called<br>");
}
}

interface Inf
{
public function Fun2();
}
class Derived extends Base implements Inf
{
function Fun2()
{
printf("Fun2() called<br>");
}

function Fun3()
{
printf("Fun3() called<br>");
}
}

$obj = new Derived();

$obj->Fun1();
$obj->Fun2();
$obj->Fun3();
Output
?> Fun1() called
Fun2() called
Fun3() called
<?php
class A {
public function insideA()
{
echo "I am in class A";
}
}
interface B
{
public function insideB();
}
class C extends A implements B
{
function insideB()
{
echo "I am in interface";
}
public function insideC()
{ Output:
echo "I am in inherited class"; I am in class A
I am in interface
} I am in inherited class
}
$obj = new C();
$obj ->insideA();
$obj ->insideB();
$obj ->insideC();
?>
Method Overloading
 Function overloading or method overloading is the ability to create multiple functions of
the same name with different implementations depending on the type of their arguments.
 In PHP overloading means the behavior of a method changes dynamically according to
the input parameter.
 There are two types of overloading in PHP.
1. Property Overloading
2. Method Overloading
 PHP supports method overloading using a magic keyword, __call.
 __call keyword
 This is a magic method that PHP calls when it tries to execute a method of a class and it
doesn't find it.
 This magic keyword takes in two arguments:
 function name
 arguments to be passed into the function.
 Its definition looks like this:
function __call(string $function_name, array $arguments)
{
}
Example
Let's understand method overloading with an example.
<?php
class Shape
{
const PI = 3.142 ;
function __call($name,$arg)
{
$x=count($arg);
if($name == 'area')
switch($x))
{
case 0 : return 0 ;
case 1 : return PI * $arg[0] ;
case 2 : return $arg[0] * $arg[1];
}
}
}
$circle = new Shape();
Output:
echo $circle->area(3); 9.426
$rect = new Shape(); 48

echo $rect->area(8,6); ?>


Method Overriding
 Function/method overriding is same as other OOPs programming languages.
 In function overriding, both parent and child classes should 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.
 The two methods with the same name and same parameter is called
overriding.
 To override a method, you redefine that method in the child class with the same
name, parameters, and return type.
 The method in the parent class is called overridden method, while the method
in the child class is known as the overriding method.
 PHP will decide which method (overridden or overriding method) to call based
on the object used to invoke the method.
 If an object of the parent class invokes the method, PHP will execute the overridden
method.
 But if an object of the child class invokes the method, PHP will execute the overriding
method.
Cloning object
 Creating copy of an object is called cloning of object.
 PHP has clone keyword that creates a shallow copy of the object.
 The magic method __clone() is used to create a deep copy of object.
 Syntax
$copyobj = clone $obj;

<?php
class CloneDemo
{
var $msg = "This is an example of cloning Object";
}
$a = new CloneDemo;
$b = clone $a;
$a->msg= "Assigned new resource";
echo "Original: " . $a->msg;
echo "Cloned: " . $b->msg;
?>
Program to create copy of an object.
Introspection in PHP:
 Introspection in PHP offers the useful ability to examine an object's
characteristics, such as its name, parent class (if any) properties, classes,
interfaces, and methods, and functions at runtime
 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 :
Serialization in PHP:
 Serialization is a technique used by programmers to preserve their working
data in a format that can later be restored to its previous form.
 Serializing an object means converting it to a byte stream representation
that can be stored in a file.
 Serialization in PHP is mostly automatic, it requires little extra work from you,
beyond calling the serialize() and unserialize() functions.
 Serialize():
The serialize() converts a storable representation of a value.
The serialize() function accepts a single parameter which is the data we
want to serialize and returns a serialized string
A serialize data means a sequence of bits so that it can be stored in a file, a
memory buffer, or transmitted across a network connection link. It is useful
for storing or passing PHP values around without losing their type and
structure.
Syntax:
serialize(value);
 unserialize():
unserialize() can use string to recreate the original variable values i.e.
converts actual data from serialized data.
Syntax:
unserialize(string);
 Example:
<?php
$a=array('Shivam','Rahul','Vilas');
$s=serialize($a);
print_r($s);
$s1=unserialize($s);
echo "<br>";
print_r($s1);
?>

Output:
a:3:{i:0;s:6:"Shivam";i:1;s:5:"Rahul";i:2;s:5:"Vilas";}
Array ( [0] => Shivam [1] => Rahul [2] => Vilas )

You might also like