Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

Unit- 03

Object Oriented
Concept in PHP

146
Advantage of OOP:-
• OOP is an approach to software development that makes it easy to map
business requirement to code modules.
• PHP is OOP language, is a type of PL principle added to PHP, that helps in
building complex, reusable web application.
• OOP invoke the use of classes to organize the data and structure of application.
• We model our problems and process using object. So object oriented
application consist object that collaborate with each other to solve the problem
• By using OOP in PHP we can create modular web application and perform any
activity in the object model structure.
• By using OOP there is opportunity for code reuses within given application as
well as across different project.

147
Basic OOP Concepts:-
• Classes:- This is a programmer-defined data type, which includes local
functions as well as local data.
• Objects:- An individual instance of the data structure defined by a class.
• Properties:- Characteristics of a class or object are known as properties.
• Methods:- The behavior of a class that is, action associated with class.
• Member Variable:- An individual instance of the data structure defined by a
class.
• 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 the existing function of a
parent class then it is called inheritance.
• Parent Class:- A class that is inherited from another class.
148
Basic OOP Concepts:-
• 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 the same function
can be used for different purposes
• Overloading − A type of polymorphism in which some or all operators have
different implementations depending on the types of their arguments.
• Data Abstraction − Any representation of data in which the implementation
details are hidden.
• Encapsulation − refers to a concept where we encapsulate all the data and
member functions together to form an object.
• Constructor & Destructor:- Object Formation and Object Deletion.

149
Creating Classes and Object in PHP:-
• A class is template for object, and • Create Object:-
object is an instance of class. • Example:-
<?php
• Syntax:- class Car
<?php {
class classname_of_class }
{ $Maruti = new Car();
$Honda = new Car();
// code is here
print_r($Maruti );
}
print_r($Honda );
?> ?>
150
Creating and Using Property:-
• Class Prosperity are very similar to Declaring Properties:-
variables.
Understanding Property Visibility:- class MyClass
• Public:- Access by any code, {
whether that code is inside or
outside the class. pubic $property1;
• Private:- Access only by the code private $property2;
inside the class. protected $property3;
• Protected:- Like private property }
but difference is any class that
inherits from the class can access.

151
Creating and Using Property:-
• Example:- // Methods
function set_name($name)
{
<?php
$this->name = $name;
class Car
}
{ function get_name()
// Properties {
public $name; return $this->name;
public $color; }
}
?>

152
Accessing Property and Method:-
• Once we have created Object we can • Example1:-
use the -> (object operator) to
<?php
access property and method of the
object. class Student
• Syntax:- {
var $roll_no;
$object->property_name; var $name;
function display()
$object->method_name([arg,…..]); {
echo “Roll No:” . $this->roll_no .
“<br>”
153
Accessing Property and Method:-
echo “Name:” . $this-> name; • Example2:-
} <?php
class Fruit
} {
$s1 = new Student; // Properties
$s1 -> roll_no =12; public $name;
$s1 -> name = “Ram”; public $color;
$s1 -> display();
// Methods
?> function set_name($name) {
Output:- Roll No: 12 $this->name = $name;
Name: Ram }

154
Accessing Property and Method:-
function get_name() { echo $apple->get_name();
return $this->name; echo "<br>";
} echo $banana->get_name();
} ?>

$apple = new Fruit(); Output:-


$banana = new Fruit(); Apple
$apple->set_name('Apple'); Banana
$banana->set_name('Banana');

155
Accessing Property and Method:-
Example:- // Method to get the area
<?php public function getArea(){
class Rectangle
{
return ($this->length * $this-
>width);
// Declare properties
public $length = 0; }
public $width = 0; }
// Create a new object from
// Method to get the perimeter Rectangle class
public function getPerimeter(){ $obj = new Rectangle;
return (2 * ($this->length + $this-
>width)); // Get the object properties values
} echo $obj->length;
156
Accessing Property and Method:-
echo $obj->width; // Call the object methods
echo “Perimeter:” . $obj-
// Set object properties values >getPerimeter() . “<br>”;
$obj->length = 30; echo “Area” . $obj->getArea();
$obj->width = 20; ?>
Output:- Perimeter: 100
// Read the object properties values
again to show the change Area: 600
echo $obj->length;
echo $obj->width;

157
Differences:-
self this
• Self keyword is not preceded by • this keyword should be preceded
any symbol. with a $ symbol.
• To access class variable and • -> symbol is used with $this as we
method using the self keyword, we have used with an object to access
use scope resolution operator :: the property of that object.
• It is refer to the static member of • It is refer to the non static member
class. of class with -> operator.
• Example:- self::<class_member> • Example:- $this -> <class_member>

158
__construct Function in PHP:-
• A constructor allows you to Example:-
initialize an object's properties class MyClass
upon creation of the object.
{
• If you create a __construct()
function, PHP will automatically function_construct()
call this function when you create {
an object from a class.
echo “Welcome to PHP constructor.
• Notice that the construct function <br>”;
starts with two underscores (__)!
}
• Constructor saves us from calling
the set_name() method which }
reduces the amount of code. $obj = new Myclass;

159
__construct Function in PHP:-
Constructor Type:- function Sample()
• Default Constructor:- {
• It has no parameters, but the value echo “Its a user define constructor of
to the default constructor can be the class Sample. <br>”;
pass dynamically. }
• We can define constructor by using function__construct()
function__construct() {
Example:- echo “Its a Pre-define constructor of the
class Sample. <br>”;
<?php }
class Sample }
{ $obj = new Sample; ?>

160
__construct Function in PHP:-
Constructor Type:- private lname;
• Parameterized Constructor:- public function__construct($fname,
• It take the parameters and you can $lname)
pass the value to the data member.
• It is use to initialize member variable {
at the time of object creation. echo “Initializing the object…. <br>”;
• -> operator is use to set value for
variable. $this->fname = $fname;
Example:- $this->lname = $lname;
<?php }
class emp public function showName()
{
{
private $fname;
161
__construct Function in PHP:-
echo “ My name is “. Mr.” . $this- Example2:-
>fname . “ ” . this->lname; <?php
} class Fruit {
} public $name;
$e1 = new emp ( “Ram”, “Mishra”); public $color;
e1->showName(); function __construct($name, $color)
Output:- {
Initializing the object…. $this->name = $name;
My name is Mr. Ram Mishra $this->color = $color;
}

162
__construct Function in PHP:-
function get_name() $apple = new Fruit("Apple", "red");
{ echo $apple->get_name();
echo “ $this->name is”; echo $apple->get_color();
} ?>
function get_color()
{ Output:- Apple is Red
return $this->color;
}
}

163
__destruct Function in PHP:-
• A destructor is called when the Syntax:-
object is destructed or the script is function_destruct()
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 (__)!
• A __destruct() function that is
automatically called at the end of
the script.

164
__destruct Function in PHP :-
Example:- $this->fname = $fname;
<?php $this->lname = $lname;
class emp }
{ public function__destruct()
Private $fname; {
private lname; echo “Destroying Objrct…..”;
public function__construct($fname, }
$lname) public function showName()
{ {
echo “Initializing the object…. <br>”;

165
__destruct Function in PHP :-
echo “ My name is “. Mr.” . $this- Example2:-
>fname . “ ” . this->lname; <?php
} class Fruit {
} public $name;
$e1 = new emp ( “Ram”, “Mishra”); public $color;
e1->showName(); function __construct($name, $color)
Output:- {
Initializing the object…. $this->name = $name;
My name is Mr. Ram Mishra }
Destroying Objrct…..
166
__destruct Function in PHP :-
function __destruct() Advantages of __destruct
{ function:-
echo "The fruit is {$this-
• Destructor is used to free up
memory allocation, so that space
>name}."; is available for new object or free
} up resources for other task.
}
$apple = new Fruit("Apple"); • It effectively make programs run
?> more efficiently and is very
useful as they carry clean up
Output:- This fruit is Apple tasks.

167
Inheritance in PHP:-
• Inheritance in OOP = When a The new sub class.
class derives from another class. • Syntax:-
• The child class will inherit all the class Parent
public and protected properties
and methods from the parent {
class. In addition, it can have its // parent class code
own properties and methods. }
• An inherited class is defined by class Child extends Parent
using the extends keyword.
{
• We create a new sub class with
all functionality of that existing // The child can be use the
class, and we add ne member to parent class code }
168
Inheritance in PHP :-
Example 1:- }}
<?php Class Rect extends Shape
class Shape {
{
public $height;
public $length;
public $width;
public function__construct($length,
$width, $height)
public function__construct($length,
$width) {
{ $this->length = $length;
$this->length = $length; $this->width = $width;
$this->width = $width; $this->height = $height;
169
Inheritance in PHP :-
}
public function intro() Output:-
{ The length is 10, the width is 20 and
echo "The length is {$this->length}, the height is 30
the width is {$this->width} and the
height is {$this->height} ";
}
}
$r = new Rect( 10, 20, 30)
$r-> intro();
?>

170
Inheritance in PHP :-
Example 2:- }
<?php public function intro()
{
class Shape
echo "The length is {$this->length} and
{ the width is {$this->width} ";
public $length; }}
public $width; Class Rect extends Shape
public function__construct($length, {
$width) public $height;
{ public function__construct($length,
$width, $height)
$this->length = $length; {
$this->width = $width; $this->length = $length;

171
Inheritance in PHP :-
$this->width = $width; $r-> intro();
$this->height = $height; $r-> introduction();
}
?>
protected function introduction()
{
echo "The length is {$this->length}, Output:-
the width is {$this->width} and the The length is 10 and the width is 20
height is {$this->height} ";
Fatal error
}
}
$r = new Rect( 10, 20, 30);

172
Inheritance in PHP :-
Example 3:- }
<?php protected function intro()
class Shape {
{ echo "The length is {$this->length}
and the width is {$this->width} ";
public $length;
}}
public $width;
Class Rect extends Shape
public function__construct($length, {
$width)
public function introduction()
{
{
$this->length = $length;
echo “The shape is Rectangle”;
$this->width = $width;

173
Inheritance in PHP :-
$this->intro();  Type of Inheritance:-
} • Single Inheritance:-
} When a subclass is derived simply
from its parent class then this
$r = new Rect( 10, 20, 30);
mechanism is known as Simple
$r-> introduction(); inheritance or Single or one level
?> Inheritance.
A
Output:-
The shape is Rectangle. The length is
10 and the width is 20 B

174
Inheritance in PHP :-
• Syntax:- • Multilevel Inheritance:-
class Parent When a subclass is derived from a
{ derived class then this mechanism is
// parent class code known as the multilevel Inheritance.
} A
class Child extends Parent
{
B
// The child can be use the parent
class code
} C

175
Inheritance in PHP :-
• Syntax:- • Example:-
class A <?php
{ class grandparent
{
}
function level1()
class B extends A
{
{
echo “ Grand-Parent <br>”;
} }}
class C extends B class parent extends grandparent
{ {
} function level2()

176
Inheritance in PHP :-
{
echo “Parent <br>”; $obj = level1();
}} $obj = level2();
class child extends parent $obj = level3();
{ ?>
function level3()
{ Output:-
echo “ Child <br>”; Grand-Parent
}} Parent
$obj = new child() Child

177
Inheritance in PHP :-
• Hierarchical Inheritance:- • Example:-
• Hierarchical Inheritance consist of <?php
Single parent class and is inherited by {
multiple child class.
public function f_a()
• In this type one class is extended by
many subclasses. {
• It is one-to-many relationship. echo “class A”;
A }
}
class b extends a
B C D {
178
Inheritance in PHP :-
public function f_b() }
{ }
echo “class B”; echo c::f_c(). “<br>”;
} echo c::f_a()
} ?>
class c extends a
{ Output:-
public function f_c() class C
{ Class A
echo “class C”;
179
Method or Function Overloading in PHP:-
• If the derived class is having a Example:-
same method name as the base <?php
class then the method in the
derived class take precedence class Base
over or overrides the base class {
method
function show()
• Function overloading or method
overloading is the ability to {
create multiple function of the echo “Display Base <br>”;
same name with different
implementation depending on }
types of their requirement. }
180
Method or Function Overloading in PHP :-
class Derived extends Base • Output:- Display Derived
{ • To call base class show() method
we can use parent::method();
function show()
• Scope resolution operator (::) is
{ used to refer function and variable
echo “Display Derived”; in base class.
} function show()
} {
$obj = new Derived(); parent::show();
$obj = show(); echo “Display Derived”;
?> }

181
Method or Function Overriding in PHP:-
• In function overriding, both Example:-
parent and child classes should <?php
have same function name with class P
and number of arguments. {
• It is used to replace parent function geeks()
method in child class.
{
• The purpose of overriding is to echo "Parent";
change the behavior of parent
class method. }
• The two methods with the same }
name and same parameter is class C extends P
called overriding. {
182
Method or Function Overriding in PHP:-
function geeks() • Output:- Parent
{ Child
echo "\nChild";
• When a method or a class is
} declared as final then overriding
} on that method or class cannot
$p = new P; be performed also inheritance
$c= new C; with the class is not possible.
$p->geeks();
$c->geeks();
?>

183
Class Overriding using Final Keyword:-
Example:- echo "<br> In the BaseClass Method
final class BaseClass display function";
{ // here you cannot extend the base class }
// as the base class is declared as final }
function ABC() $obj1 = new BaseClass;
{ $obj1->display();
echo "<br> In the BaseClassMethod $obj1->ABC();
ABC function"; Output:-
}
function display() In the BaseClass Method ABC function
In the BaseClass Method display function
{

184
Method Overriding using Final Keyword :-
Example:- echo "<br /> In the Base cLass ABC
class BaseClass function";
{ // Final method – display }
// this cannot be overridden in base class
}
final function display() class DerivedClass extends BaseClass
{ {
echo "<br /> In the Base class function ABC()
display function"; {
} echo "<br /> In the Derived class ABC
function";
function ABC() }
{ }

185
Method Overriding using Final Keyword :-
Cloning Object:-
$obj1 = new DerivedClass; • Object cloning is the process in
$obj1->display(); PHP to create a copy of an object.
$obj1->ABC(); • An object copy is created by using
the clone keyword.
Output:- • When an object is cloned, PHP will
perform a shallow copy of all
In the Base class display function object property.
In the Derived class ABC function
• Syntax:-$copy_object_name =
clone $object to_be_copied

186
Cloning Object :-
Example:- $obj->amount = 5;
<?php $copy = clone $obj;
class MyClass print_r($copy);
{ ?>
public $color;
• Output:-
public $amount; MyClass Object ([color] => red
} [amount] => 5)
$obj = new MyClass();
$obj->color = 'red';

187
__clone() method to break references:-
Example:- $value = 5;
<?php $obj = new MyClass();
class MyClass { $obj->amount = &$value;
public $amount; $copy = clone $obj;
public function __clone() $obj->amount = 6;
{ print_r($copy);
$value = $this->amount; ?>
unset($this->amount); Output:-
$this->amount = $value; MyClass Object ([amount] => 5)
} } // or $amount = $value;
188
Introspection in PHP:-
• Introspection is the ability of a • You don’t need to know which
program to examine an object’s methods or properties are
characteristics, such as its name, defined when you write your
parent class (if any), properties, code.
and methods. • Instead, you can discover that
• PHP offers a large number of information at runtime, which
functions that you can use to makes it possible for you to write
accomplish the task. generic debuggers, serializes,
• With introspection, you can profilers.
write code that operates on any
class or object.
189
Introspection in PHP:-

190
Introspection :-
Example1:- }
<?php
?>
if(class_exists(‘GPG'))
{
Output:- Not exist
$obj =new GPG();
echo "This is www.gpg.ac.in";
}
else
{
echo "Not exist";

191
Introspection :-
Example2:- else
<?php
class GPG {
{ echo "Not exist";
//decl }
}
?>
if(class_exists(‘GPG'))
{
$obj =new GPG(); Output:- This is www.gpg.ac.in
echo "This is www.gpg.ac.in";
}

192
Introspection :-
Example3:- print_r($class_method);
<?php
?>
class GPG
{
Output:- Array ([0]=> co [1]=> it)
function co() {}
Function it() {}
}
$obj =new GPG();
$class_methods =
get_class_method(‘GPG’);
193
Serialization and unserialization in PHP:-
• Serialization is a technique used • Example:-
by programmer to preserve <html>
their working data in a format <body>
that can later be restore to its <?php
previous form. $s_data = serialize(array("Red",
"Green", "Blue"));
• Sterilizing object means echo $s_data;
converting it to byte stream $us_data = unserialize($s_data) ;
representation that can stored echo $us_data;
in a file. ?>
• Serialization in PHP is mostly </body></html>
automatic process.
194
Serialization in PHP:-
• Output:- • Example 2:-
a:3:{i:0;s:3:"Red";i:1;s:5:"Green"; <?php
i:2;s:4:"Blue";} class Student
Array ([0]=>Red [1]=>Green $age = 19;
[2]=>Blue
function show_Age()
{
echo $this->age;
}
}
195
Serialization in PHP:-
$stud = new Student;
Sstud->show_Age();
$s_obj = serialize($stud);
$fp = fopen(“gpg.txt”, “w”);
fwrite($fp, $s_obj);
fclose($fp);
$us_obj = unserialize($s_obj);
$us_obj->show_Age();
?>
196

You might also like