0% found this document useful (0 votes)
45 views54 pages

WBP Unit 3

This document provides an overview of Object-Oriented Programming concepts in PHP, including class definitions, object creation, constructors, destructors, inheritance, and serialization. It explains the syntax for creating classes and objects, the role of constructors and destructors, and different types of inheritance. Additionally, it covers the concept of serialization for storing and transmitting data in PHP.

Uploaded by

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

WBP Unit 3

This document provides an overview of Object-Oriented Programming concepts in PHP, including class definitions, object creation, constructors, destructors, inheritance, and serialization. It explains the syntax for creating classes and objects, the role of constructors and destructors, and different types of inheritance. Additionally, it covers the concept of serialization for storing and transmitting data in PHP.

Uploaded by

pagareankita29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54

Unit 3

Object Oriented Concepts in PHP


Class
• A class is defined by using the class keyword, followed by the name of the class
and a pair of curly braces ({}).
• Class is a programmer-defined data type, which includes local methods and local
variables.
• It is a collection of objects.

• Syntax to Create Class in PHP


<?php
class MyClass
{
// Class properties and methods go here
}
?>
• Below are the rules for creating a class in PHP.

• The class name should start with a letter


• The class name cannot be a PHP reserved word
• The class name cannot contain spaces
• Defining PHP Classes
• The general form for defining a new class in PHP is as follows −
Here is the description of each line −

<?php The special form class, followed by the name of


the class that you want to define.
class phpClass {
var $var1; A set of braces enclosing any number of variable
declarations and function definitions.
var $var2 = "constant string";
Variable declarations start with the special form
var, which is followed by a conventional $
function myfunc ($arg1, $arg2) { variable name; they may also have an initial
assignment to a constant value.
[..]
Function definitions look much like standalone
} PHP functions but are local to the class and will
[..] be used to set and access object data

}
?>
Class creation
<?php
class Student {
// property decaration
var $roll_no=1; //1 is default value

function showrollno() // method def


{
echo $this->roll_no;
}
}
?>
Creating Object
• To create an object of a given class, use ‘new’ keyword.

• Syntax:
• $object=new classname();
• E.g
• $s1=new Student();
<?php
class Student {
Accessing
var $roll_no; Properties and
var $name; methods of an
{
function display()
object
echo "Roll No: " . $this->roll_no ."<br>";
echo "Name: " . $this->name ;
}
}
$s1=new Student;
OR
$s1=new Student();
$s1->roll_no=10;
$s1->name="Kimaya";
$s1->display() ;
?>
Output:
Roll No: 10
Name: Kimaya
• In PHP, to see the contents of the class, use var_dump().
• The var_dump() function is used to display the structured
information (type and value) about one or more variables.
• Syntax:
• var_dump($obj);
• Object:
• A class defines an individual instance of the data structure.
• We define a class once and then make many objects that belong to it. Objects are also known as an
instance.

• An object is something that can perform a set of related activities.

• Syntax:
<?php
class MyClass
{
// Class properties and methods go here
}
$obj = new MyClass;
var_dump($obj);
?>
<?php
class Books{
public function name(){
echo "Drupal book";
}
public function price(){ Output:
echo "900 Rs/-";
Drupal book
} 900 Rs/-
}
//To create php object we have to use a new operator. Here php object is the object of the
Books Class.
$obj = new Books();
$obj->name();
$obj->price();
?>
<?php
class demo
{
private $a= “Hello TYCM";
public function display()
{
echo $this->a;
}
}
$obj = new demo();
$obj->display();
?>

The variable $this is a special variable and it refers to the same object ie.
itself.
<?php
class Books { function setTitle($par){
/* Member variables */ $this->title = $par;
}
var $price;
var $title; function getTitle(){
echo $this->title ." <br/>";
}
/* Member functions */ }
function setPrice($par){
$obj=new Books();
$this->price = $par; $obj->setPrice(2000);
} $obj->getPrice();
$obj->setTitle("STE");
$obj->getTitle();
function getPrice(){ ?>

echo $this->price ."<br/>";


}
PHP OOP - Constructor
• Constructor Functions are special type of functions which are called
automatically whenever an object is created.
• PHP provides a special function called _ _construct() to define a
constructor.
• You can pass as many as arguments you like into the constructor
function.
• The _ _construct() method always have the public visibility factor.
<?php
class Student {
$s1=new Student;
public $roll_no;
public $name;
$s1-> display() ;
function __construct() ?>
{
$this->roll_no = 10;
$this->name = "Kimaya";
}
public function display()
{
echo "Roll No: ". $this->roll_no ."<br>";
echo "Name: " . $this->name ;
}
}
<?php
class Fruit { $apple = new Fruit("Apple", "red");
public $name; echo $apple->get_name();
public $color; echo "<br>";
echo $apple->get_color();
function __construct($name, $color) { ?>
$this->name = $name;
$this->color = $color;
}
function get_name() {
return $this->name;
}
function get_color() {
return $this->color;
}
}
Types of Constructor
• 1.Default Constructor
• It has no parameters , but the values to the default constructor can be passed
dynamically.
• We can define constructor by using
• function _ _ construct()

• 2.Parameterized Constructor
• It takes the parameters and also you can pass different values to the data
members.
• It is used to initialize member variables at the time of object creation.
• The -> operator is used to set value for the variables.
1.Default Constructor

<?PHP
class Tree
{
function Tree()
{
echo "Its a User-defined Constructor of the class Tree";
}

function __construct()
{
echo "Its a Pre-defined Constructor of the class Tree";
}
}
$obj= new Tree();
?>

• Output:
• Its a Pre-defined Constructor of the class Tree
2.Parameterized Constructor

<?php
function show_details()
{
class Employee echo $this->name." : ";
echo "Your position is ".$this->profile."\n";
{ }
Public $name; }
Public $position;
$employee_obj= new Employee("Rakesh","developer");
function __construct($name,$position) $employee_obj->show_details();
{
$employee2= new Employee("Vikas","Manager");
// This is initializing the class properties $employee2->show_details();
$this->name=$name; ?>
$this->profile=$position;
Output:
} Rakesh : Your position is developer
Vikas : Your position is Manager
• Following example will create one constructor for Books class and it
will initialize price and title for the book at the time of object creation.

function __construct( $par1, $par2 ) {


$this->title = $par1;
$this->price = $par2;
}

• Now we don't need to call set function separately to set price and
title. We can initialize these two member variables at the time of
object creation only.
• Destructor
• Like a constructor function you can define a destructor function using
function __destruct(). You can release all the resources with-in a
destructor.
• The destructor method is called when the PHP code is executed
completely by its last line by using PHP exit() or die() functions.
<?php
class SampleClass
{
function __construct()
{
echo "In constructor, ";
$this->name = "Class object! ";
}
function __destruct()
{
echo "destroying " . $this->name . "\n";
}
}
$obj = new Sampleclass();
?>
Output:
In constructor, destroying Class object!
Constructors Destructors

Accepts one or more arguments. No arguments are passed. Its void.

function name is _construct(). function name is _destruct()

It has same name as the class. It has same name as the class with prefix ~tilda.

Constructor is involved automatically when the object is created. Destructor is involved automatically when the object is destroyed.

Used to de-initialize objects already existing to free up memory for new


Used to initialize the instance of a class.
accomodation.

Used to initialize data memebers of class. Used to make the object perform some task before it is destroyed.

Constructors can be overloaded. Destructors cannot be overloaded.

It is called each time a class is instantiated or object is created. It is called automatically at the time of object deletion .

Allocates memory. It deallocates memory.

Multiple constructors can exist in a class. Only one Destructor can exist in a class.

If there is a derived class inheriting from base class and the object of the derived
The destructor of the derived class is called and then the destructor of base class
class is created,
just the reverse order of
the constructor of base class is created and then the constructor of the derived
constructor.
class.

The concept of copy constructor is allowed where an object is initialized from the
No such concept is allowed.
adress of another object .
• Inheritance is an important principle of object oriented programming
methodology. Using this principle, relation between two classes can
be defined. PHP supports inheritance in its object model.

• PHP uses extends keyword to establish relationship between two


classes.

• Syntax
• class B extends A
• where A is the base class (also called parent called) and B is called a
subclass or child class.
• Child class inherits public and protected methods of parent class.
• This allows us to write the code only once in the parent and then use it in both parent and child
classes.
• Child class may redefine or override any of inherited methods.
• If not, inherited methods will retain their functionality as defined in parent class, when used with
object of child class.
• Child class can have it's own methods too, which will not be available to the parent class.
• Child class can also override a method defined in the parent class and provide its own
implementation for it.

• <?php
• class A{
• //properties, constants and methods of class A
• }
• class B extends A{
• //public and protected methods inherited
• }
• ?>
Types of Inheritance
• Single Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Multiple Inheritance
Single Inheritance

• Syntax:
• Class Parent
•{
• //
•}
• Class Child extends Parent
•{
• //The child can use the parent’s class code
•}
Multilevel Inheritance
Multiple inheritance
• Syntax:

• class child_class_name extends parent_class_name {


• use trait_name;
• ...
• ...
• child_class functions
•}
class Sample extends Geeks {
<?php use forGeeks;
public function geeksforgeeks() {
// Class Geeks echo "\nGeeksforGeeks";
class Geeks { }
public function sayhello() { }
echo "Hello";
} $test = new Sample();
}
$test->sayhello();
$test->sayfor();
// Trait forGeeks
$test->geeksforgeeks();
trait forGeeks {
?>
public function sayfor() {
Output:
echo " Geeks";
Hello Geeks
}
GeeksforGeeks
}
• Interface (Using Class along with Interface):
• Syntax:

• class child_class_name extends parent_class_name implements


interface_name1,
<?php public function insidemultiple() {
class A { echo "\nI am in inherited class";
public function insideA() { }
echo "I am in class A"; }
}
} $geeks = new multiple();
interface B { $geeks->insideA();
public function insideB(); $geeks->insideB();
} $geeks->insidemultiple();
class Multiple extends A implements B { ?>
Output:
I am in class A
function insideB() {
I am in interface
echo "\nI am in interface";
I am in inherited class
}
<?php
class Mobile public function getModel()
{ {
echo "<br>".$this->model;
private $color;
}
public function setColor($color) }
{ $ph=new Samsung();
$this->color=$color; $ph->setColor("RED");
} $ph->getColor();
public function getColor() $ph->setModel("Samsung Galaxy");
{ $ph->getModel();
?>
echo $this->color;
}
}
class Samsung extends Mobile Output:
{ RED
private $model; Samsung Galaxy
public function setModel($model)
{
$this->model=$model;
}
Cloning Object
• The clone keyword is used to create a copy of an object.
• If any of the properties was a reference to another variable or object,
then only the reference is copied.
• Objects are always passed by reference, so if the original object has
another object in its properties, the copy will point to the same
object.
• This behavior can be changed by creating a __clone() method in the
class.
In shallow copy both the objects point to same reference.
In deep copy separate copy of references is created for each object.
Introspection
• Introspection in PHP offers the useful ability to examine classes,
interfaces, properties, and methods.
• PHP offers a large number functions that you can use to accomplish the
task.
• You can use these functions to extract basic information about classes
such as their name, the name of their parent class, and so on.

• 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 an object’s parent class
• is_subclass_of() – checks whether an object has a given parent class
<?php if (class_exists("Introspection")) {
class Introspection $introspection = new Introspection();
echo "The class name is: " . get_class($introspection) . "n";
{
$introspection->description();
public function description() {
}
echo "I am a super class for the Child class.n";
} if (class_exists("Child")) {
} $child = new Child();
$child->description();
class Child extends Introspection
if (is_subclass_of($child, "Introspection")) {
{
echo "Yes, " . get_class($child) . " is a subclass of
public function description() { Introspection.n";
echo "I'm " . get_class($this) , " class.n"; }
echo "I'm " . get_parent_class($this) , "'s else {
child.n"; echo "No, " . get_class($child) . " is not a subclass of
Introspection.n";
}
}
} }
• The output of the above code should be as follows:

The class name is: Introspection


I am a super class for the Child class.
I'm Child class.
I'm Introspection's child.
Yes, Child is a subclass of 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.
• All property variables of object are contained in the string and methods are
not saved. This string can be stored in any file.

• Syntax:
• serialize(value);
<?php
$data = serialize(array("Red", "Green", "Blue"));
echo $data;
?>

• Output:
• a:3:{i:0;s:3:"Red";i:1;s:5:"Green";i:2;s:4:"Blue";}
• unserialize():
• unserialize() can use string to recreate the original variable values i.e.
converts actual data from serialized data.

• Syntax:
• unserialize(string);
• <?php
• $data = serialize(array("Red", "Green", "Blue"));
• 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" }
• 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 )
END

You might also like