Unit 3 Apply Object Oriented Concepts in PHP
3.1 Creating classes and objects
3.2 Constructor and Destructor
3.3 Inheritances, overloading, overriding, cloning object
3.4 Introspection, Serialization
3.1 Creating classes and objects:-
Creating classes:-
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 go inside the braces:
Syntax :-
<?php
class Student
{
// code goes here... properties and methods
}
?>
Creating objects:-
To create an object of a given class
We use “new” keyword followed by class name for which we want to create object
Syntax:-
$object_name=new class_name;
Example:-
If we are having class Student as shown above then we create stud object for class student
$stud=new Student;
i.e stud is object of class Student.
Prepared by:-Ms Khade A.M Page 1
Accessing Properties and Methods using object:-
once we have an object
we can use the -> ( object operator ) to access Properties and Methods of the class.
Syntax:-
$object_name -> properties _name;
$object_name -> methods _name ([arg1, arg2 ..........]);
Example:-
$stud ->name;
$stud ->show ();
Example
<?php
class Student
{
// Properties
public $name;
public $rno;
// Methods
function set_name($name)
{
$this->n1 = $name;
}
function get_name()
{
return $this->n1;
}
//for Roll No
function set_roll_no($rno)
{
$this->r1 = $rno;
}
function get_roll_no()
{
return $this->r1;
}
Prepared by:-Ms Khade A.M Page 2
$s1 = new Student(); //object create
$s1->set_name('Ram');
echo $s1->get_name();
echo "<br>";
$s1->set_roll_no(1);
echo $s1->get_roll_no();
echo "<br>";
?>
Output:-
$this Keyword :-
The $this keyword refers to the current object, and is only available inside methods.
change the value of the $name property?
There are two ways:
1. Inside the class (by adding a set_name() method and use $this):
Example
<?php
class Student
{
public $name;
function set_name($name)
{
$this->n1 = $name;
}
Prepared by:-Ms Khade A.M Page 3
}
$s1 = new Student ();
$s1->set_name("Ram");
?>
2. Outside the class (by directly changing the property value):
Example
<?php
class Student
{
public $name;
}
$s1 = new Student ();
$s1->name = "Ram";
?>
PHP - instanceof
You can use the instanceof keyword to check if an object belongs to a specific class:
Example
<?php
$s1 = new Student();
var_dump($s1 instanceof Student); //true
?>
Prepared by:-Ms Khade A.M Page 4
PHP has three visibility keywords –
1.public
2. private
3.protected.
Public :- A class member declared with public keyword is accessible from anywhare.
Protected :-A protected member is accessible from within its class and by inheriting
class.
Private :-private member can only be accessed by the same class in which it is defined
and is not visible to anything outside it.
3.2 Constructor and Destructor [ construct() destruct() ]
A constructor allows you to initialize an object's properties upon creation of the object.
If you create a construct() function, PHP will automatically call this function when you
create an object from a class.
Notice that the construct function starts with two underscores ( )
We see in the example below, that using a constructor saves us from calling the
set_name() method which reduces the amount of code:
Constructor types:
Default Constructor: It has no parameters, but the values to the default constructor can
be passed dynamically.
Parameterized Constructor: It takes the parameters, and also you can pass different
values to the data members.
Copy Constructor: It accepts the address of the other objects as a parameter.
Prepared by:-Ms Khade A.M Page 5
Constructor in inheritance
If the parent class has constructor defined in it, it can be called within child class's constructor
by
1. construct
2. parent::__construct
Scope resolution operator ::
However, if child class doesn't define a constructor, it inherits the same from is base class.
Program:-
<?php
class Student
{
// Properties
public $name;
public $rno;
// Methods
function construct ($name) // constructer
{
$this->n1 = $name;
}
function get_name()
{
return $this->n1;
}
$s1 = new Student("Ram"); //object
echo $s1->get_name();
?>
Output:-
Prepared by:-Ms Khade A.M Page 6
Program2:- constructer having name as class name
<?php
class Student
{
// Properties
public $name;
public $rno;
// Methods
function Student() //class == constructer
{
echo " constructer having name as class name Student";
}
function construct() //1
{
echo "Student constructer having name construct"."<br>";
}
$s1 = new Student();
$s1->Student();
?>
Output:-
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 ( )!
Prepared by:-Ms Khade A.M Page 7
The example below has a construct() function that is automatically called when you
create an object from a class, and a destruct() function that is automatically called at
the end of the script:
PHP code is executed completely by its last line by using PHP exit() or die() functions.
As constructors and destructors helps reducing the amount of code, they are very useful!
Program:-
<?php
class Student
{
// Properties
public $name;
public $rno;
// Methods
function construct($name) //constructor
{
$this->n1 = $name;
}
function get_name()
{
return $this->n1;
}
function destruct() //destructor
{
echo "destructor called,My Name is {$this->n1}";
}
$s1 = new Student("Ram"); //object
echo $s1->get_name();
?>
Output:-
Prepared by:-Ms Khade A.M Page 8
3.3 Inheritance, overloading, overriding, cloning object
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)
from which we inherit is called the parent class.
The parent class is also known as the base class.
Base class = old class = parent class = super class
Derived class = new class = child class = sub class
Types of Inheritance in PHP
PHP supports various types of inheritance like JAVA/C++. The below table shows the list of
inheritance types and the supporting status in PHP.
Inheritance Type Support in PHP
Single Inheritance YES
Multilevel Inheritance YES
Hierarchical Inheritance YES
Multiple Inheritance NO
Prepared by:-Ms Khade A.M Page 9
1. 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. Let‟s understand the same with an
example. It is popularly known as simple inheritance. This type of inheritance in PHP
language remains the same as JAVA, C++, etc
2. Multilevel Inheritance
PHP supports Multilevel Inheritance. In this type of inheritance, we will have more than 2
classes. In this type of inheritance, a parent class will be inherited by a child class then that child
class will be inherited by the child class. This type of inheritance in PHP language remains the
same as C++ etc.
Prepared by:- Ms Khade A.M Page 10
2. Multiple Inheritance
Not supported in php
PHP doesn‟t support multiple inheritance but by using Interfaces in PHP or using Traits in PHP
instead of classes, we can implement it.
Traits (Using Class along with Traits):
The trait is a type of class which enables multiple inheritance.
Classes, case classes, objects, and traits can all extend no more than one class but can extend
multiple traits at the same time.
3. Hierarchical Inheritance
PHP supports Hierarchical inheritance. Hierarchical inheritance is the type of inheritance in
which a program consists of a single parent and more than one child class. Let‟s understand the
same with this example. This type of inheritance in PHP language remains the same as JAVA,
C++, etc.
Prepared by:- Ms Khade A.M Page 11
Program:
<?php
//class a(Base) b (child) c (child)
class a
{
function showa()
{
echo "this showa of base class a";
echo "<br>";
}
}
//b (child) parent class a
class b extends a
{
function showb()
{
echo "this showb class b";
echo "<br>";
}
}
class c extends a
{
function showc()
{
echo "this showc class c";
echo "<br>";
}
}
$b1=new b(); //child class
$b1->showb();
$b1->showa();
$c1=new c();
$c1->showc();
$c1->showa();
?>
Prepared by:- Ms Khade A.M Page 12
Output:-
Que.Write a Program to implements following types inheritance using given classes with its
properties
1. Single
2. Multilevel
3. Hierarchical
Class person class student class employee
Name Branch company name
Age roll no salary
Prepared by:- Ms Khade A.M Page 13
Overloading:- (Compile Time Polymorphism)
Function overloading is a feature that permits making creating several methods with a
similar name that works differently from one another in the type of the input parameters
it accepts as arguments.
Method overloading is performed within class.
In case of method overloading, parameter must be different.
Method overloading is the example of compile time polymorphism.
Program:-
<?php
//class a(Base) b (child) c (child)
class a
{
function show()
{
echo "in class a show function"."<br>";
}
public function display()
{
echo "in class a display function"."<br>";
}
}
//b (child) parent class a
class b extends a
{
function show()
{
echo "in class b show function"."<br>";
//call to base class function show
parent::show(); //Scope resolution operator ::
}
}
$b1=new b();
$b1->show();
?>
Prepared by:- Ms Khade A.M Page 14
Output:-
Prepared by:- Ms Khade A.M Page 15
Overriding:- (Run Time Polymorphism)
In function overriding, the parent and child classes have the same function name with and
number of arguments
Method overriding occurs in two classes that have IS-A (inheritance) relationship.
In case of method overriding, parameter must be same.
Method overriding is the example of run time polymorphism.
Program:-
<?php
//class a(Base) b (child) c (child)
class a
{
function show()
{
echo "in class a show function"."<br>";
}
//b (child) parent class a
class b extends a
{
function show()
{
echo "in class b show function"."<br>";
}
}
$b1=new b();
$b1->show();
$a1=new a();
$a1->show();
?>
Prepared by:- Ms Khade A.M Page 16
Output:-
Prepared by:- Ms Khade A.M Page 17
Cloning object:-
Object cloning is process in PHP to create a copy of an object.
An object copy is created by using the clone keyword
When object is cloned PHP will perform a shallow copy of the objects properties
Syntax
$new_object_name=clone $old_object_to_be_copied
Example
$b1=new b(); //object of class b
$newb= clone $b1; // copy of object b1 of class b
Prepared by:- Ms Khade A.M Page 18
3.4 Introspection and Serialization
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. In order
to help you understand introspection, I‟ll provide a brief overview of some of PHP‟s classes,
methods, and functions using examples in PHP to highlight how they are used.
Examining classes:
Introspection Functions to be used to examining classes are,
1. class_exists ()
2. get_class_methods ()
3. get_class_vars ()
4.get_parent_class ()
1. class_exists ()
Returns True if passed class name exists if not then false
Syntax
$yesno= class_exists („class_name‟);
We can use function instead of class_exists
get_declared_classes ()
this returns an array of all defined classes
Syntax
$classesnames= get_declared_classes ();
2. get_class_methods ()
This function Returns an array of class methods name
Syntax
Prepared by:- Ms Khade A.M Page 19
$methods= get_class_methods („class_name‟);
3. get_class_vars ()
This function Returns an array of properties of class (variables names)
Syntax
$variablename= get_class_vars („class_name‟);
4. get_parent_class ()
This function Returns an name of parent class or false if there is no parent class
This function accepts as parameters object of class or class name
Syntax
$baseclass= get_parent_class („class_name‟);
Program:-
<?php
class a
{
//properties of class (variables names)
public $name;
public $rno;
//Methods
function sum ()
{
}
function add ()
{
}
function sub ()
{
Prepared by: Ms Khade A.M Page 20
//inheritance
class b extends a
{
function Show()
{
}
}
class c extends b
{
//1 class_exists
if(class_exists('a'))
{
echo "Class presnt";
echo "<br>";
}
else
{
echo "Class not presnt";
echo "<br>";
}
//2 get_class_methods
$cm=get_class_methods ('b');
echo "class methods names :- ";
print_r($cm);
echo "<br>";
//3 get_class_vars
$cv=get_class_vars ('a');
echo "variable names :- ";
var_dump($cv);
//4 get_parent_class
echo "<br>";
$p=get_parent_class('c');
echo "parent class :- ";
print_r($p);
?>
Prepared by:- Ms Khade A.M Page 21
Output:-
Examining an Object:
Introspection Functions to be used to examining an object are,
1. is_object ()
2. get_class ()
3. get_object_vars ()
4. method_exists ()
1. is_object ():-
Returns True if passed parameter is an object
Syntax
$yesno=is_object ($obj);
2. get_class ()
Returns the name of the class of an object.
Syntax
$classname= get_class ($obj);
3. get_object_vars ()
Get the properties of given object.
Syntax
$array= get_object_vars ($obj); //obj-----class ---- variable
Prepared by:- Ms Khade A.M Page 22
4. method_exists ()
Check if the class method exit or not.
Syntax
$ yesno = method_exists ($obj,$method_name);
Program:-
class a
{
//properties of class (variables names)
public $name;
public $rno;
//Methods
function sum ()
{
}
function add ()
{
}
function sub ()
{
}
//inheritance
class b extends a
{
function Show()
{
}
}
class c
{
public $comp_name;
public $Branch;
}
Prepared by:- Ms Khade A.M Page 23
$a1=new a();
$b1=new b();
$c1=new c();
//1 is_object
$obj=is_object($a1);
echo "object or not :- ";
var_dump($obj);
echo "<br>";
//2 get_class
$cm=get_class ($b1);
echo "class names :- ";
print_r($cm);
echo "<br>";
//3 get_object_vars
$objv=get_object_vars ($c1);
echo "variable names :- ";
var_dump($objv);
echo "<br>";
//4 method_exists
$p=method_exists($c1,'add');
echo "parent class :- ";
var_dump($p);
?>
Output:-
Prepared by:- Ms Khade A.M Page 24
Serialization
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.
We can use two functions serialize ( ) and unserialize() to implement our own form of
persistent object
For example
$encode= serialize ($somedata);
$somedata= unserialize ($encode);
Serialize ()method returns a string containing a byte-stream representation of any value
that can be stored in PHP.
Unserialize () method can use this string to recreate the original variable values
Syntax
serialize(value);
While saving an object, all the variables of the object will be saved, but the functions will
not be saved.
After serialization of an object the byte version can be stored in a file.
To unserialize () an object in another PHP file, the class must be defined in that file.
This can be done by including rile where the class has been defined
Syntax
unserialize( value)
Prepared by:- Ms Khade A.M Page 25
Que.The following program shows how object is serialized and stored in a text file, then the
object is unserialize
Program:-
<?php
class Student
var $age =18;
function show_Age()
echo this-> age;
$stud= new Student
$stud->show_Age();// Outputs 10
$sri_obj= serialize ($stud); / $stud is serialized, converted to string
$fp=fopen ("a. txt", “w”);
fwrite ($fp, $sri_obj); / / storing serialized obj into the file
fclose ($fp);
$us_obj= unserialize ($sri_obj); // new object $us_obj created
$us_obj->show_Age(); // outputs 10
?>
Prepared by:- Ms Khade A.M Page 26
Output:-
Storing serialized obj into the file a.txt
PHP has two hooks for objects during the serialization and unserialization process
1. sleep( )
2. wakeup()
These methods are used to notify objects that they are being serialized or unserialize.
Serialize() checks if our class has a function with the magic name sleep(), If so, that
function is executed prior i.e. just before to any serialization.
It can clean up the object and is supposed to return an array with the names of all
variables of that object that should be serialized.
if the method doesn't return anything then Null is serialized. The sleep() function is
useful if we have very large objects which do not heed to be saved completely.
Unserialize() checks for the presence of a function with the magic name wakeup(). if
present, this function can reconstruct any resources that the object may have.
Prepared by:- Ms Khade A.M Page 27
Program:-
<?php
class Student
{
public $name;
public $rno;
public function construct($name, $rno)
{
$this->name = $name;
$this->rno = $rno;
}
public function sleep()
{
echo "Sleep calling <br>";
return array('name','rno');
}
public function wakeup()
{
echo "Wakeup calling <br>";
}
}
$s1=new Student("Ram",01);
$data= serialize($s1);
echo $data."<br>";
$un=unserialize($data);
print_r($un);
?>
Output:-
Prepared by:- Ms Khade A.M Page 28