Chapter-3(WBP)
Chapter-3(WBP)
Chapter-3(WBP)
Unit III
Apply Object Oriented Concepts in PHP Page 1
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
• Syntax
<?php
class Fruit {
// code goes here...
}
?>
Unit III
Apply Object Oriented Concepts in PHP Page 2
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
• Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
• In a class, variables are called properties and functions are called methods!
3.
Define Objects
• 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.
• Objects of a class are created using the new keyword.
• In the example below, $apple and $banana are instances of the class Fruit:
• Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();
Unit III
Apply Object Oriented Concepts in PHP Page 3
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
In the example below, we add two more methods to class Fruit, for setting and
getting the $color property:
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit();
$apple->set_name('Apple');
$apple->set_color('Red');
echo "Name: " . $apple->get_name();
echo "<br>";
echo "Color: " . $apple->get_color();
?>
1. Inside the class (by adding a set_name() method and use $this):
Example
<?php
class Fruit {
public $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");
?>
Example
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
?>
5. PHP - instanceof
You can use the instanceof keyword to check if an object belongs to a specific
class:
Example
<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit); ?>
this keyword is used inside a class, generally within the member functions to
access non-static members of a class(variables or functions) for the current object.
Unit III
Apply Object Oriented Concepts in PHP Page 5
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
• In the program above, we have created a private variable in the class with
name $name and we have two public methods setName() and getName() to
assign a new value to $name variable and to get its value respectively.
• Whenever we want to call any variable of class from inside a member
function, we use $this to point to the current object which holds the variable.
• We can also use $this to call one member function of a class inside another
member function.
• If there is any static member function or variable in the class, we cannot refer
it using the $this.
For example:
printf("Ram is %d years old.\n", $ram->age); // property access
$ram->birthday(); // method call
$ram->set_age(21); // method call with arguments
Unit III
Apply Object Oriented Concepts in PHP Page 6
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Example:
<?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.
1. PHP Constructor:-
Let's take the example of a class Person which has two properties, fname and
lname, for this class we will define a constructor for initialising the class
properties(variables) at the time of object creation.
<?php
class Person {
// first name of person
private $fname;
// last name of person
private $lname;
// Constructor
public function __construct($fname, $lname) {
echo "Initialising the object...<br/>";
$this->fname = $fname;
$this->lname = $lname;
}
// public method to show name
public function showName() {
Unit III
Apply Object Oriented Concepts in PHP Page 7
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
• While earlier, we were using the -> operator to set values for the variables or
used the setter methods, in case of a constructor method, we can assign
values to the variables at the time of object creation.If a class has a
constructor then whenever an object of that class is created, the constructor is
called.
2. PHP Destructor:-
PHP Destructor method is called just before PHP is about to release any object
from its memory. Generally, you can close files, clean up resources etc in the
destructor method. Let's take an example,
<?php
class Person {
// first name of person
private $fname;
// last name of person
private $lname;
// Constructor
public function __construct($fname, $lname) {
echo "Initialising the object...<br/>";
$this->fname = $fname;
$this->lname = $lname;
}
// Destructor
public function __destruct(){
// clean up resources or do something else
echo "Destroying Object...";
}
// public method to show name
public function showName() {
echo "The Legend of India: " . $this->fname . " " . $this->lname . "<br/>";
}
}
// creating class object
$j = new Person("Swami", "Vivekananda");
$j->showName();
?>
• As we can see in the output above, as the PHP program ends, just before it
Unit III
Apply Object Oriented Concepts in PHP Page 8
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
PHP initiates the release of the object created, and hence the destructor method
is called.
• The destructor method cannot accept any argument and is called just before
the object is deleted, which happens either when no reference exist for an
object or when the PHP script finishes its execution.
3.3 1. Inheritance
• The maruti class is inherited from the car class.This means that the maruti
class can use the public $name and $color properties as well as the public
__construct() and intro() methods from the car class because of inheritance.
The maruti class also has its own method: message().
2. Overloading
1. 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.
2. Overloading in PHP provides means to dynamically create properties and
methods.
3. These dynamic entities are processed via magic methods, one can
establish in a class for various action types.
4. The overloading methods are invoked when interacting with properties or
methods that have not been declared or are not visible in the current scope
5. All overloading methods must be defined as Public. After creating an
object for a class, we can access a set of entities that are properties or
methods not defined within the scope of the class.
6. Such entities are said to be overloaded properties or methods, and the
process is called overloading.
7. For working with these overloaded properties or functions, PHP magic
methods are used.
8. Most of the magic methods will be triggered in object context except
__call() method which is used in dynamic context.
9. __call() and __callStatic() are called when somebody is calling a
Unit III
Apply Object Oriented Concepts in PHP Page 10
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
3. Overriding
1. It is the same as other OOPs programming languages.
2. In this function, both parent and child classes should have the same
function name and number of arguments.
3. It is used to replace the parent method in child class.
4. The purpose of function overriding is to change the behavior of the parent
class method.
5. The two functions with the same name and the same parameter are called
function overriding.
Unit III
Apply Object Oriented Concepts in PHP Page 11
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
Example
<?php
class aicte {
function helloWorld() {
echo "Parent"."<br>";
}
}
class msbte extends aicte {
function helloWorld() {
echo "\nChild";
}
}
$p = new aicte;
$c= new msbte;
$p->helloWorld();
$c->helloWorld();
?>
4. Cloning Object
1. The clone keyword is used to create a copy of an object.
2. If any of the properties was a reference to another variable or object, then
only the reference is copied.
3. 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.
4. This behavior can be changed by creating a __clone() method in the class.
$obj->amount = 6;
// The copy is changed
print_r($copy);
?>
• In this the data is actually completely copies.
• In this everything is duplicated and all values are copies into a new instances.
• Advantage of deep copy is that the A & B do not depend on each other but the
process is
• relatively slower and more expensive.
• In shallow copy B points to object A’s memory location whereas in deep copy
all things in object
• A’s memory location get copied to object B’s location.
<?php
class MyClass {
public $amount;
public function __clone() {
$value = $this->amount;
unset($this->amount); // Unset breaks references
$this->amount = $value;
}
}
// Create an object with a reference
$value = 5;
$obj = new MyClass();
$obj->amount = &$value;
// Clone the object
$copy = clone $obj;
// Change the value in the original object
$obj->amount = 6;
// The copy is not changed
print_r($copy);
echo "<br>";
print_r($obj);
?>
3.4 1. Introspection
Introspection is the ability of a program to examine an object characteristics such
as its name,parent class,properties and method.
(i) class_exists():
• This function is used to determine whether a class exists.It takes a string
and return a Boolean value.
• Syntax-
$yes_no=class_exists(classname);
• This function returns TRUE if classname is a defined class, or FALSE
(ii) get_class_method()
• This function returns the names of the class methods.
(iii) get_parent_class():
• return the class name of an object parent class
(iv) is_subclass_of():
• check whether an object has parent class.
<?php
if(class_exists('cwipedia'))
{
$ob=new cwipedia();
echo "This is cwipedia.in";
}
else
{
echo "Not exist";
}
?>
output:Not exist
<?php
class vesp
{
function a()
{
echo "hey CO6I";
}}
if(class_exists('vesp'))
{
$ob=new vesp();
echo "This is ves.ac.in";
echo "<br>";
echo $ob->a();
}
Unit III
Apply Object Oriented Concepts in PHP Page 14
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
else
{
echo "Not exist";
}
?>
Output:
hey CO6I
"This is ves.ac.in
2.
serialize
• The serialize() function converts a storable representation of a value.
• Syntax
serialize(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.
<?php
Example
// Complex array
$myvar = array(
'hello',
42,
array(1, 'two'),
'apple'
);
// Convert to a string
$string = serialize($myvar);
// Printing the serialized data
echo $string;
?>
• Output:
a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";}
3. Unserialize()
• The unserialize() is an inbuilt function php that is used to unserialize the
given serialized array to get back to the original value of the complex array,
$myvar.
• Syntax:
unserialize( $serialized_array )
• Below program illustrate both serialize() and unserialize() functions:
Program:
<?php
// Complex array
$myvar = array(
'hello',
Unit III
Apply Object Oriented Concepts in PHP Page 15
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)
42,
array(1, 'two'),
'apple'
);
// Serialize the above data
$string = serialize($myvar);
// Unserializing the data in $string
$newvar = unserialize($string);
// Printing the unserialized data
print_r($newvar);
?>
Output:
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
Unit III
Apply Object Oriented Concepts in PHP Page 16