OOP in PHP

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 41

Unit-5

Apply object oriented


concepts in PHP
Object oriented concept
• Procedural programming is about writing procedures or functions
that perform operations on the data, while object-oriented
programming is about creating objects that contain both data and
functions.
Advantages of OOP
1. OOP is faster and easier to execute

2. OOP provides a clear structure for the programs

3. OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and
makes the code easier to maintain, modify and debug
4. OOP makes it possible to create full reusable applications with less

code and shorter development time.


What are Classes and Objects?
• Procedural Classes and objects are the two main aspects of object-
oriented programming.
• a class is a template
for objects, and an
object is an instance
of a class.
• When the individual
objects are created,
they inherit all the
properties and
behaviors from the
class, but each object
will have different
values for the
properties.
Class in PHP
 we have a class named Fruit. A Fruit can have properties like name,
color, weight, etc. We can define variables like $name, $color, and
$weight to hold the values of these properties.
 When the individual objects (apple, banana, etc.) are created, they

inherit all the properties and behaviors from the class, but each
object will have different values for the properties.
• A class is a collection of
objects.
• Object has properties and
behavior
• Characteristics of class are
properties of object
• Behavior of class is action
associated with it called
method
Define a class
 A class is defined by using <?php
the class keyword, followed by the class Fruit
name of the class and a pair of { // Properties
curly braces ({}). public $name;
public $color;
 All its properties and methods go // Methods
inside the braces: function set_name($name)
Syntax {
<?php $this->name = $name;
class classname }
{ function get_name()
{
// code goes here...
return $this->name;
} }
?> }
?>
Define an Object
 Classes are nothing without objects! We <?php
can create multiple objects from a class. class Fruit
Each object has all the properties and { // Properties
methods defined in the class, but they will public $name;
have different property values. public $color;
// Methods
 Objects of a class is created using function
the new keyword. set_name($name)
$apple = new Fruit(); {
$banana = new Fruit(); $this->name = $name;
$apple->set_name('Apple'); }
$banana->set_name('Banana'); function get_name()
echo $apple->get_name(); {
return $this->name;
echo "<br>";
}
echo $banana->get_name(); }
?> Apple Banana
Define an Object & Property visibility
//Class example class Myclass
<?php {
class Car public $p1;
{ private $p2;
//Nothing to see here; protected $p3;
} }
$maruti=new Car(); Public can be accessed by any code,
$honda=new Car(); whether code is inside the class or outside
print_r($maruti); class.
print_r($honda); Private can be accessed by only by code
?> inside the class, only methods in the class
Car Object ( ) Car Object ( ) can be access its contents.
Protected can be accessed within the
class and by classes derived from that
class.
Sample program
<?php $stud1=new Student();
class Student $stud2=new Student();
{ //Properties
public $name; $stud1->set_name("Xyz");
public $city; $stud2->set_name("ABC");
//Methods
function set_name($name) echo $stud1->get_name();
{ echo $stud2->get_name();
$this->name=$name; ?>
} The $this keyword refers to the
function get_name() current object, and is only
{ available inside methods.
1. Inside the class (by adding a
return $this->name;
set_name() method and use
}
$this):
}
2. Outside the class (by directly

changing the property value):


PHP constructor
 A constructor allows to initialize an
object's properties upon creation of the <?php
object. //Creating the constructor
 If we create a __construct() function,
class MyClass
PHP will automatically call this function
{
when we create an object from a class.
 construct function starts with two
function __construct()
underscores (__)! {
 Default Constructor: no parameters echo "This is defualt constructor";
}
}
$obj=new MyClass();
?>
PHP Parameterized constructor
//Parameterized Constructor public function showName()
<?php {
class Person echo "My name is ".$this->fname." ".
{ $this->lname;
private $fname; }
private $lname; }
//Constructor //Creating object
public $p=new Person("Andy","Rubin");
function __construct($fname,$lname) $p->showName();
{ ?>
echo "Intialising Object"; Intialising ObjectMy name is Andy
$this->fname=$fname; Rubin
$this->lname=$lname;
}
//method to show name
PHP Destructor
 A destructor is called when the object is <?php
destructed or the script is stopped or class MyExample
exited. {
 If we create a __destruct() function,
function __construct()
PHP will automatically call this function
{
at the end of the script.
 Notice that the destruct function starts
print "In constructor <br>";
with two underscores (__)! }
function __destruct()
{
//Destructor syntax print "Destroying ".__CLASS__."<br>";
function __destruct() }
{ }
//Clean up here $obj=new MyExample();
} ?> In constructor
Destroying MyExample
PHP Inheritance
 Inheritance is mechanism of
extending an existing class by class Parent
inheriting a class. {
 We create a new sub class with all //The parent's class code
functionality of that existing
}
class, we can add new members
to new sub class. class Child extends Parent
 Subclass & parent class {
 Use of extend keyword //The child can use thee
 The child class will inherit all the parent's method
public and protected properties }
and methods from the parent
class. In addition, it can have its
own properties and methods.
PHP Single Inheritance
 When a subclass is derived <?php
simply from its parent class . class A
{function dis1()
class Parent {echo "hello parent class";}
{ }
class B extends A
//The parent's class code
{//function dis1()
}
function dis2()
class Child extends Parent
{echo "hello child class";}
{ } $obj=new B();
//The child can use thee $obj->dis1();
parent's method $obj->dis2();
} ?>hello parent class hello
child class
PHP Multilevel Inheritance
 When a subclass is derived from a class parents extends grandparent
derived class. { function dis2()
Syntax of Multilevel inheritance { echo "Parents<br>"; }
class A }
{ } class child extends parents
class B extends class A { function dis3()
{ } { echo "child<br>";}
class C extends class B }
{ } $obj=new child();
Program $obj->dis1();
<?php $obj->dis2();
class grandparent $obj->dis3();
{ function dis1() ?>
{echo "Grand-Parents<br>"; Grand-Parents
} Parents
} child
PHP Hierarchical Inheritance
 A single parent class & that class }
is inherited by multiple child class. class C extends A
 1 class is extended by many
{
subclasses. public function display3()
<?php { echo "Child C"; }
class A }
{ $obj=new C();
public function display1() $obj->display1();
{ echo "Parent A<br>"; } $obj->display3();
} $obj1=new B();
class B extends A $obj1->display1();
{ $obj1->display2();
public function display2() ?>
{ echo "Child B"; }
PHP Multiple Inheritance
 Inheriting features of more than 1 class C extends A
base class into a single class. By {
using interfaces or traits in PHP use B;
implemented
public function display3()
<?php
{ echo "Child C"; }
class A
}
{
$obj=new C();
public function display1()
$obj->display1();
{ echo "Parent A<br>"; }
$obj->display2();
}
$obj->display3();
trait B// class B
?>
{
Parent A
public function display2() Parent B
{ echo "Parent B<br>"; } Child C
PHP traits
 Traits define actual implementation trait message1
of each method within each class, {
traits are just chunks of code public function msg1()
injected in a class in PHP.
{ echo "OOP is fun! "; }
 Traits are not interfaces at all.
}
Traits can define both static
class Welcome
members and static methods.
 To reuse methods freely in several
{
use message1;
independent classes in different
class hierarchies.
}
 Traits reduces complexity.
$obj = new Welcome();
$obj->msg1();
 PHP does not allow multiple
?>
inheritance so traits can remove
this gap. OOP is fun!
<?php
PHP Interfaces
 Interfaces allow we to specify what methods a class should implement.
 An interface is like class but no data variables, only method declaration

no implementation.
 Class can inherit from one class but class can implement 1 or more

interfaces.
<?php
interface InterfaceName
{
public function someMethod1();
public function someMethod2($name, $color);
public function someMethod3() : string;
}
?>
PHP Interface example1
<?php $fruit = new apple();
interface fruit $fruit->color();
{ ?>
public function color(); OUTPUT: RED
}
class apple implements fruit
{
public function color()
{
echo “RED";
}
}
PHP Interface example2
<?php class C extends A implements B
//Class A i.e. Parent A {
class A public function display2()
{ {
public function display1() echo "Parent B<br>";
{ }
echo "Parent A<br>"; public function display3()
} {
} echo "Child C";
//Interface B i.e. Parent B }
interface B }
{ $obj=new C();
public function display2(); $obj->display1();
} $obj->display2();
Parent A Parent B Child C $obj->display3();
?>
PHP Access Modifier
 Properties and methods can have <?php
access modifiers which control class Fruit
where they can be accessed. {
public $name;
There are three access modifiers:
protected $color;
 public - the property or method
private $weight;
can be accessed from everywhere. }
This is default
 protected - the property or
$mango = new Fruit();
method can be accessed within $mango->name = 'Mango'; // OK
the class and by classes derived $mango->color = 'Yellow'; // ERROR
from that class $mango->weight = '300'; // ERROR
 private - the property or method ?>
can ONLY be accessed within the
class
PHP Access Modifier
<?php private function set_weight($n
class Fruit )
{ { // a private function
public $name; $this->weight = $n;
public $color; }
public $weight; }

function set_name($n) $mango = new Fruit();


{ // a public function (default) $mango->set_name('Mango'); //
$this->name = $n; OK
} $mango->set_color('Yellow'); //
protected function set_color($ ERROR
n) $mango->set_weight('300'); //
{ // a protected function ERROR
$this->color = $n; ?>
}
PHP Inheritance Example (public)
<?php $this->length=$length;
class Shape $this->width=$width;
{ $this->height=$height;
public $length; }
public $width; public function
public function __construct($length, showInformation()
$width)
{
{ echo "The length is {$this->
$this->length=$length; length},
$this->width=$width; The width is {$this-> width},
}} The height is {$this-> height}
";
class Rect extends Shape
}}
{
$r=new Rect(10,20,30);
public $height;
public function __construct($length,$width, $r->showInformation();
$height)
PHP Inheritance Example (public, protected)
<?php public $height;
class Shape public function __construct($length,$width,
$height)
{
{ $this->length=$length;
public $length;
$this->width=$width;
public $width;
$this->height=$height;
public function __construct($length,
}
$width)
protected function showInformation()
{
{
$this->length=$length;
echo "The length is {$this-> length},
$this->width=$width;
The width is {$this-> width},
}
The height is {$this-> height}
public function showInfo()
";
{
}}
echo "The length is {$this->length}
$r=new Rect(10,20,30);
and width is {$this->width}";
$r->showInfo();
}}
$r->showInformation();//error
class Rect extends Shape
?>
{
The length is 10 and width is 20
PHP Inheritance Example
<?php }
class Shape class Rect extends Shape
{ {
public $length; public function
public $width; showInformation()
public function __construct($length, {
$width)
echo "The shape of rectange ";
{ $this->showInfo();//Call
$this->length=$length; prtected function from child
$this->width=$width; class
} }
protected function showInfo() }
{ $r=new Rect(10,20);
echo "The length is {$this- $r->showInformation();
>length} and width is {$this- ?> The shape of rectangle
PHP Concrete Class
 The class which implements an <?php
interface called concrete class. interface InterfaceExample
{
 It must implement all methods
public function display2();
defined in an interface.
}
 It can be inherited by another class, class ClassEx implements InterfaceExample
but not an abstract class. {
 It can implement any no. of public function display2()
interfaces {
echo "Display 2 implemented in class<br>";
}
}
$obj=new ClassEx;
$obj->display2();
?>
Display 2 implemented in
class
PHP Abstract Class & Abstract Methods
 It is a class that has at least one
abstract method. <?php
 Use of keyword abstract. abstract class Base
 It can inherit 1 or more interfaces. {
 It can not inherit more than 1 //this is abstract function
abstract class. abstract function printData();
 Abstract class can not inherit from }
non abstract class class Derived extends Base
{
 Abstract method only name &
arguments no other code. function printData()
{
echo "Derived class";
}
Derived class }
$obj=new Derived;
$obj->printData();
PHP Property overloading
 It is used to create dynamic properties in
the object context.
 A property associated with a class
instance, & if it is not declared within
the scope of the class, it is considered as
overloaded property.
 To perform the operations, we should
define magic methods as follows
PHP Property overloading
<?php }
class Toys public function __unset($name)
{ {
private $str; unset($this->str[$name]);
public function __set($name,$value) echo "\$$name is unset ";
{ }
$this->str[$name]=$value; }
} $obj= new Toys;
public function __get($name) /*setters and getters on dyanamic properties*/
{ $obj->overloaded_property="CAR";
echo "Overloaded Property name= ".$this- echo $obj->overloaded_property."\n\n"
>str[$name]."<br>"; /*Operations with dyanmic properties values*/
} isset($obj->overloaded_property);
public function __isset($name) unset($obj->overloaded_property);
{ isset($obj->overloaded_property);
if(isset($this->str[$name])) ?>
{ Overloaded Property name= CAR
echo "Property \$$name is set "; Property $overloaded_property is set
} $overloaded_property is unset Property
else $overloaded_property is not set
{ echo "Property \$$name is not set"; }
PHP Function overloading
<?php $s=new addition;
class addition echo("Return one value: ".
{ //__call magic function $s->add(10)."<br>");
function __call($name_of_function,$args) echo("Return two values: ".
{ if($name_of_function=='add') $s->add(10,20)."<br>");
{ echo("Return three values: ".$s-
switch(count($args)) >add(10,20,30)."<br>");
{ ?>
case 1: Return one value: 10
return $args[0]; Return two values: 30
Return three values: 60
case 2:
return $args[1]+$args[0];
 In PHP overloading with same name
case 3:
function can’t be possible so with the help of
return $args[2]+$args[1]+$args[0]; magic function overloading is done.
}  If same function name error:
} cannot redeclare function().
}
}
PHP method overriding
 Here both parent & child classes
should have same function name
and no. of arguments.
 It is used to replace parent method
in child class.
 Purpose is to change behavior of
parent class method.
 2 methods of same name & same
parameter called overriding.
PHP method overriding
<?php class square extends Shape
class Shape {
{ public $height;
public $length; public function __construct($len,$width,$height)
public $width; { $this->length=$len;
public function __construct($len,$width) $this->width=$width;
{ $this->height=$height;
$this->length=$len; }
$this->width=$width; public function intro()
} { echo "The length is ".$this->length." and the
public function intro() width is ".$this->width."and hieght is ".$this-
{ >height."<br>";
echo "The length is ".$this->length." and the width }
is ".$this->width."<br>"; }
} $s=new square(10,30,50);
} $s->intro();
?>
The length is 10 and the width is 30and
hieght is
PHP Final Class
 A class declared as final can not be {
extended In future. Or can not be echo "Inside the child class";
inherited. }
 It may contain final & non final methods }
$obj=new B();
<?php $obj->disp();
final class A ?>
{
public function disp() Output-
{ Fatal error: class B may not inherit
echo "Inside the parent class"; from final class (A)
}
}
class B extends A
{
function disp()
PHP Final method
 A final method prevents method }
overriding. }
$obj=new B();
<?php $obj->disp();
class A ?>
{ PHP Fatal error: Cannot override
final public function disp() final method A::disp()
{
echo "Inside the Parent class";
}
}
class B extends A
{
function disp()
{
echo "Inside child class";
PHP cloning object
 Object cloning is process to create a <?php
copy of an object. class Sample
 An object copy is created by using {
magic method __clone(). public $variable1;
 Without __clone(), the internal public $variable2;
objects of the new object will be function _construct($variable1,$variable2)
references to same object in { $this->variable1=$variable1;
memory as the internal objects of the $this->variable2=$variable2; } }
original object that was cloned. $variable1=new Sample("ABC","Software
Developer");
$variable2=$variable1;
print_r($variable1);
print("<br>");
print_r($variable2);
?>
Sample Object ( [variable1] => [variable2]
=> )
Sample Object ( [variable1] => [variable2]
=> )
Simple Copy without clone
<?php $this->green=$green;
class obj $this->blue=$blue;
{ $this->red=$red;
public $id; }
public $size; }
public $color; $color=new Color(23,42,223);
function __construct($id,$size,$color) $obj1=new Obj(23,"small",$color);
{ $obj2=clone $obj1;
$this->id=$id; $obj2->id++;
$this->size=$size; $obj2->color->red=255;
$this->color=$color; $obj2->size="big";
} echo "<pre>";print_r($obj1);
echo "<pre>";print_r($obj2);
} ?>
class Color
{
public $green;
public $red;
public $blue;
function __construct($green,$red,$blue)
{
Shallow clone(copy)
<?php $this->green=$green;
class obj $this->blue=$blue;
{ $this->red=$red;
public $id; }
public $size; }
public $color; $color=new Color(23,42,223);
function __construct($id,$size,$color) $obj1=new Obj(23,"small",$color);
{ $obj2=clone $obj1;
$this->id=$id; $obj2->id++;
$this->size=$size; $obj2->color->red=255;
$this->color=$color; $obj2->size="big";
} echo "<pre>";print_r($obj1);
echo "<pre>";print_r($obj2);
} ?>
class Color
{
public $green;
public $red;
public $blue;
function __construct($green,$red,$blue)
{
Deep clone(copy)
<?php {
class obj public $green;
{ public $red;
public $id; public $blue;
public $size; function __construct($green,$red,$blue)
public $color; {
function __construct($id,$size,$color) $this->green=$green;
{ $this->blue=$blue;
$this->id=$id; $this->red=$red;
$this->size=$size; }
$this->color=$color; }
} $color=new Color(23,42,223);
function __clone() $obj1=new Obj(23,"small",$color);
{ $obj2=clone $obj1;
$green=$this->color->green; $obj2->id++;
$red=$this->color->red; $obj2->color->red=255;
$blue=$this->color->blue; $obj2->size="big";
$this->color=new Color($green,$red,$blue); echo "<pre>";print_r($obj1);
} echo "<pre>";print_r($obj2);
} ?>
class Color
Simple copy Shallow clone Deep clone
obj Object obj Object obj Object
( ( (
[id] => 24 [id] => 23 [id] => 23
[size] => big [size] => small [size] => small
[color] => Color Object [color] => Color Object [color] => Color Object
( ( (
[green] => 23 [green] => 23 [green] => 23
[red] => 255 [red] => 255 [red] => 42
[blue] => 223 [blue] => 223 [blue] => 223
) ) )
) ) )
obj Object obj Object obj Object
( ( (
[id] => 24 [id] => 24 [id] => 24
[size] => big [size] => big [size] => big
[color] => Color Object [color] => Color Object [color] => Color Object
( ( (
[green] => 23 [green] => 23 [green] => 23
[red] => 255 [red] => 255 [red] => 255
[blue] => 223 [blue] => 223 [blue] => 223
) ) )
) ) )
Introspection
 The ability to examine an object’s
characteristics, such as its name,
parent class, properties, classes,
interfaces, methods.
<?php
if(class_exists('Demo'))
{
$demo=new Demo();
echo "This is Demo class";
}
else
{
echo "Class does not exists";
}
?>
Output- Class does not exists
Serialization
 It is technique to preserve their working <?php
data in a format that can later be $s_data=serialize(array('Welcome','to','
restored to its previous form. PHP'));
 Serializing an object means converting print_r($s_data."<br>");
it to a byte stream representation that $us_data=unserialize($s_data);
can be stored in a file or sent across n/w.
print_r($us_data);
 Serialize() function converts a storable
?>
representation of a value.
Output-
 It accepts a single parameter which is to
a:3:{i:0;s:7:"Welcome";i:1;s:2:"to";i:2;s:3:"PHP";}
be serialize.
Array([0]=>Welcome [1]=>to [2]=>PHP)
 Unserialize() can use string to recreate 
a: array
original variable values.  3:no. of elements
 i: index0-2
 0: index value
 S: string
 7: no. of characters
 “welcome”: value

You might also like