SlideShare a Scribd company logo
1 of 63
UNIT III
Object–Oriented PHP:
Contents
Object Oriented Programming – Basics PHP constructs for OOP
– Advanced OOP features – Introspection Functions – OOP
Style in PHP
Object Oriented Programming
● OOP stands for Object-Oriented Programming.
● 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.
Object-oriented programming has several advantages over procedural programming:
● OOP is faster and easier to execute
● OOP provides a clear structure for the programs
● OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
● OOP makes it possible to create full reusable applications with less code and shorter
development time
The object-oriented approach(Terminology)
● Class: This is a programmer-defined data type, which includes local functions as well as
local data.
● Object: (Also known as object instance, or instance.)
○ An individual instance of the data structure defined by a class.
○ You define a class once and then make many objects that belong to it.
● Member variable: (Also known as property, attribute, or instance variable.) One of the
component pieces of data in a class definition.
● Member function: (Also known as method.) A member that happens to be a function.
● Inheritance:
○ The process of defining a class in terms of another class.
○ The new (child) class has all the member data and member function definitions from the
old (parent) class by default but may define new members or “override” parent functions
and give them new definitions.
○ We say that class A inherits from class B if class A is defined in terms of class B in this
way.
○ Parent class (or superclass or base class): A class that is inherited from by another
class.
○ Child class (or subclass or derived class): A class that inherits from another class.
Single inheritance
● PHP allows a class definition to inherit from another class, using the extends clause. Both
member variables and member functions are inherited.
Multiple inheritance
● PHP offers no support for multiple inheritance as in Java. Each class inherits from, at most,
one parent class (though a class may implement many interfaces).
Encapsulation − refers to a concept where we encapsulate all the data and member functions
together to form an object.
○ It is also known as information hiding concept
Constructor − refers to a special type of function which will be called automatically whenever there
is an object formation from a class.
Destructor − refers to a special type of function which will be called automatically whenever an
object is deleted or goes out of scope.
Basic PHP Constructs for OOP
Defining classes
class myclass {
public $var1;
public $var2 ;
public function myfunc ($arg1, $arg2)
{
……..
}
}
The form of the syntax is as described, in order, in the following list:
● The special form class, followed by the name of the class that you want to define.
● A set of braces enclosing any number of variable declarations and function definitions.
● Variable declarations start with the special form public, private, or protected, which
is followed by a conventional $ variable name; they may also have an initial assignment
to a constant value.
Creating instances
After we have a class definition, the default way to make an instance of that class is by
using the new operator
Example: objectname = new classname;
$box = new TextBoxSimple;
$box->display();
Accessing member variables
In general, the way to refer to a member variable from an object is to follow a variable
containing the object with -> and then the name of the member
Example : $variablename =object->member variable
$textbox = $box->body_text;
Example:
<?php
class Fruit {
// Properties
public $name;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();// object creation
$apple->set_name('Apple');
echo $apple->get_name();
?>
After we have a class definition, the default way to make an instance of that class is by
using the new operator
Example: objectname = new classname;
$box = new TextBoxSimple;
$box->display();
In general, the way to refer to a member variable from an object is to follow a variable
containing the object with -> and then the name of the member
Example : $variablename =object->member variable
$textbox = $box->body_text;
Constructor functions
● A constructor allows you to initialize an object's properties upon creation of the
object.
● The correct way to arrange for data to be appropriately initialized is by writing a
constructor function — a special function called __construct(), which will be called
automatically whenever a new instance is created.
● The construct function starts with two underscores (__)
Example 1
<?php
class text
{
public $a;
function __construct($a)// constructor
{
$this->a = $a;
}
function display()
{
echo $this->a;
}
}
$text1= new text("hello");
$text1->display();
?>
Example 2
<?php
class student
{
public $id;
public $name;
function __construct($id,$name)
{
$this->id = $id;
$this->name = $name;
}
function display1()
{
echo $this->id;
}
function display2()
{
echo $this->name;
}}
$s1= new student(2,"arun");
echo "<center>";
echo "<table border='1'>";
echo "<th>id</th><th>name</th>";
echo "<tr><td>";
$s1->display1();
echo "<td>";
$s1->display2();
echo "</td></tr>";
echo "</center>";
?>
Destructor functions
● A destructor is called when the object is destructed or the script is stopped or exited.
● The destruct() function will be called automatically at the end of the script.
● The destruct function starts with two underscores(__)
<?php
class text
{
public $a;
function __construct($a)// constructor
{
$this->a = $a;
}
function __destruct()
{
echo $this->a;
}
}
$text1= new text("hello");
?>
Inheritance
● Inheritance in OOP = When a class derives from another class.
● The child class will inherit all the public and protected properties and methods from
the parent class. In addition, it can have its own properties and methods.
● An inherited class is defined by using the extends keyword.
● PHP class definitions can optionally inherit from a parent class definition by using the
extends clause.
● The syntax is:
class Child extends Parent {
<definition body>
}
The effect of inheritance is that the child class (or subclass or derived class) has the
following characteristics:
● Automatically has all the member variable declarations of the parent class (or
superclass or base class)
● Automatically has all the same member functions as the parent, which (by default) will
work the same way as those functions do in the parent
Example:
<?php
class student {
public $name;
public $mark1;
public $mark2;
public function __construct($name, $mark1,$mark2) {
$this->name = $name;
$this->mark1 = $mark1;
$this->mark2 = $mark2;
}
public function display() {
echo "name=".$this->name."<br>";
echo "mark1=".$this->mark1."<br>";
echo "mark2=".$this->mark2."<br>";}
}
class addition extends student
{
public $total;
public function add()
{
$total=$this->mark1+$this-
>mark2;
echo "total=".$total;;
}
}
$s1 = new addition("Abi",50,60);
$s1->display();
$s1->add();
?>
Chained subclassing
● PHP does not support multiple inheritance but does support chained subclassing.
● This is a fancy way of saying that, although each class can have only a single parent,
classes can still have a long and distinguished ancestry (grandparents, great-
grandparents, and so on). (multilvel)
● Also, there’s no restriction on family size;
● each parent class can have an arbitrary number of children. (Hierarchical)
Example1:(multilevel inheritance)
<?php
class student {
public $name;
public $m1;
public $m2;
public function get() {
$this->name = "arun";
$this->m1 =60;
$this->m2 =70;
}
public function display() {
echo "name=".$this->name."<br>";
echo "mark1=".$this->m1."<br>";
echo "mark2=".$this->m2."<br>";
class total extends student
{
public $total;
public function computeTotal()
{
$this->total= $this->m1+$this->m2;
echo "total=".$this->total."<br>";
}
}
class avg extends total
{
public $avg;
public function calculateAvg()
{
$this->avg=$this->total= $this->total/2;
echo "avg=".$this->avg;
}
}
$avg1 = new avg();
$avg1->get();
$avg1->display();
$avg1->computeTotal();
$avg1->calculateAvg();
?>
Example2:(Hierarchical inheritance)
<?php
class arith{
public $m1;
public $m2;
public function get() {
$this->m1 =60;
$this->m2 =70;
}
public function display() {
echo "number1=".$this->m1."<br>";
echo "number2=".$this->m2."<br>";
}
}
class addition extends arith
{
public $add;
public function computeadd()
{
$this->add= $this->m1+$this->m2;
echo "add=".$this->add."<br>";
}
}
class subtraction extends arith
{
public $sub;
public function calculatesub()
{
$this->sub=$this->m1-$this->m2;
echo "sub=".$this->sub;
}
}
$a1=new addition();
$s1=new subtraction();
$a1->get();
$a1->display();
$a1->computeadd();
$s1->get();
$s1->calculatesub();
?>
Overriding method (functions)
● Method overriding allows a child class to provide a specific implementation of a method
already provided by its parent class.
● Method overriding occurs when a subclass (child class) has the same method as the
parent class
● To override a method, you redefine that method in the child class with the same name,
parameters, and return type.
● The method in the parent class is called overridden method,
● while the method in the child class is known as the overriding method.
● The code in the overriding method overrides (or replaces) the code in the overridden
method.
PHP will decide which method (overridden or overriding method) to call based on the
object used to invoke the method.
● If an object of the parent class invokes the method, PHP will execute the
overridden method.
● But if an object of the child class invokes the method, PHP will execute the
overriding method.
Example:
<?php
class base{
public function display() {
echo "parent method";
}
}
class sub extends base
{
public function display()
{
echo "child method";
}
}
$sub1=new sub();
$sub1->display();
?>
Scoping issues
● Names of member variables and member functions are never meaningful to calling
code on their own , they must always be reached via the -> construct
● The names visible within member functions are exactly the same as the names
visible within global functions — that is, member functions can refer freely to
other global functions but can’t refer to normal global variables unless those
variables have been declared global inside the member function definition.
Advanced OOP features
1.Public, Private, and Protected Members
Public:(default access speicifier)
Unless you specify otherwise, properties and methods of a class are public. That is to say,
they may be accessed in three possible situations:
● The property or method can be accessed from everywhere. This is default
○ From outside the class in which it is declared
○ From within the class in which it is declared
○ From within another class that implements the class in which it is declared
Example:
<?php
class student {
var $name;// default access specifier public
public $mark1,$mark2;
function get($name, $mark1,$mark2)
{
$this->name = $name;
$this->mark1 = $mark1;
$this->mark2 = $mark2;
}
function display()
{
echo "name=".$this->name."<br>";
echo "mark1=".$this->mark1."<br>";
echo "mark2=".$this->mark2."<br>";}
}
$s1 = new student();
$s1->get("nithya",50,60);
$s1->display();
?>
Private:
● The property or method can ONLY be accessed within the class
● The private member cannot be referred to from classes that inherit the class in
which it is declared and cannot be accessed from outside the class.
Protected:
● The property or method can be accessed within the class and by classes derived from
that class
● A protected property or method is accessible in the class in which it is declared, as
well as in classes that extend that class
Example:
<?php
class student {
protected $name;
protected $mark1,$mark2;
function get($name, $mark1,$mark2) {
$this->name = $name;
$this->mark1 = $mark1;
$this->mark2 = $mark2;
}
function display() {
echo "name=".$this->name."<br>";
echo "mark1=".$this->mark1."<br>";
echo "mark2=".$this->mark2."<br>";}
}
class addition extends student
{
function add()
{
$total=$this->mark1+$this->mark2;
echo "total=".$total;;
}}
$s1 = new addition();
$s1->get("nithi",50,60);
$s1->display();
$s1->add();
?>
2.Interfaces
● Interfaces allow you to specify what methods a class should implement.
● An interface consists of methods that have no implementations, which means the
interface methods are abstract methods.
● All the methods in interfaces must have public visibility scope.
● Interfaces are different from classes as the class can inherit from one class only
whereas the class can implement one or more interfaces.
Example:
interface Mail
{
public function sendMail();
}
class Report implements Mail
{
// Definition goes here
}
Program:
<?php
interface Arithmetic
{
public function add();
}
class Addition implements Arithmetic
{
var $p,$q;
public function add() {
$this->p=50;
$this->q=40;
$this->sum=$this->p+$this->q;
echo "add=".$this->sum;
}
}
$obj1 = new Addition();
$obj1->add();
?>
3.Constants
● A constant is somewhat like a variable, in that it holds a value but is really more like a
function because a constant is immutable. Once you declare a constant, it does not
change.
● The constant’s name does not have a leading $, as variable names do.
● Constants cannot be changed once it is declared.
● Class constants can be useful if you need to define some constant data within a class.
● A class constant is declared inside a class with the const keyword.
● We can access a constant from outside the class by using the class name followed by
the scope resolution operator (::) followed by the constant name
● we can access a constant from inside the class by using the self keyword followed by
the scope resolution operator (::)
Program:
<?php
class area
{
const pi=3.14; // const value
var $r,$a;
function get($r)
{
$this->r = $r;
}
function compute()
{
$this->a= self::pi*$this->r*$this->r;
echo "area of circle=".$this->a;
}
}
$area1 = new area();
$area1->get(6);
$area1->compute();
?>
4.Abstract classes
● An abstract class is one that cannot be instantiated, only inherited.
● An abstract class is a class that contains at least one abstract method.
● An abstract method is a method that is declared, but not implemented in the code.
● An abstract class or method is defined with the abstract keyword
abstract class MyAbstractClass
{
abstract function myAbstractFunction()
{
}
}
Program:
<?php
abstract class rect
{
var $l,$b,$a;
function get()
{
$this->l=6;
$this->b=5;
}
abstract function compute();
}
class area extends rect
{
function compute()
{
$this->a=$this->l*$this->b;
echo "area of rect =".$this->a;
}
}
$area1 = new area();
$area1->get();
$area1->compute();
5.Simulating class functions
● In PHP, there are no declarations in a class definition that indicate whether a function
is intended for per-instance or per-class use.
● But PHP does offer a syntax for getting to functions in a class even when no instance
is handy.
● The :: syntax operates much like the -> syntax does, except that it joins class names
to member functions rather than instances to members
Program:
<?php
class calculator
{
var $a,$b,$c;
function compute()
{
$a=6;
$b=6;
$c=$a+$b;
echo "add=".$c;
}
}
calculator::compute();
?>
6.Calling parent functions
Calling parent constructors
● To call the constructor of the parent class from the constructor of the child class,
use following syntax
○ parent::__construct(arguments)
Automatic calls to parent constructors
if a subclass lacks a constructor function(not having constructor) and a superclass has
one, the superclass’s constructor will be invoked
Program:
<?php
class student
{
protected $name;
protected $m1;
protected $m2;
public function __construct($name)
{
$this->name = $name;
}
}
class details extends student
{
public function __construct($name,$m1,$m2)
{
student::__construct($name); // call to parent constructor
$this->m1=$m1;
$this->m2=$m2;
}
public function compute()
{
echo $this->name;
echo "<br>";
$total= $this->m1+$this->m2;
echo $total;
}
}
$d= new details("nithi",60,70);
$d->compute();
?>
7.Simulating method overloading
● Method overloading contains same function name and that function performs
different task according to number of arguments
● In PHP overloading means the behavior of method changes dynamically according to
the input parameter.
● The __call() method is invoked automatically when a non-existing method or
inaccessible method is called. The following shows the syntax of the __call() method:
○ public __call ( string $name , array $arguments )
● The __call() method accepts two arguments:
● $name is the name of the method that is being called by the object.
● $arguments is an array of arguments passed to the method call.
Program:
<?php
class Shape {
const PI = 3.142 ;
function __call($name,$arg)
{
$count=count($arg);
if($count==1)
{
$c= self::PI*$arg[0];
echo "area of circle=".$c;
}
elseif($count==2)
{
$c= $arg[0]*$arg[1];
echo "area of rect=".$c;
} }
}
$s = new Shape();
$s->area(8,6);
echo "<br>";
$s->area(3);
?>
8.Serialization
● Serialization of data means converting it into a string of bytes in such a way that you can produce
the original data again from the string (via a process known, unsurprisingly, as unserialization).
● PHP provides a mechanism for storing and loading data with PHP types across multiple HTTP
requests.
● This mechanism boils down to two functions: serialize() and unserialize().
Serialization
● A string representation of any object in the form of byte-stream is obtained by serialize()
function in PHP
● All property variables of object are contained in the string and methods are not saved. This string
can be stored in any file
Deserialization
● To retrieve the object from the byte stream, there is unserialize() function
Sample serialization output
O:8:"stdClass":1:{s:4:"data";s:10:"Some data!";}
● The O stands for the type of the serialized string. In this case the O maps to a PHP
object.
● The 8 seperated by the colons represents the length of the name of the class
● The following 1 represents the number of properties the serialized object contains
which are stored within curly brackets
● Each property is stored as a serialized string representing the property name, a
semicolon and a serialized string representing the value.
Program 1:
<?php
class test1
{
public $name;
function get($arg){
$this->name=$arg;
}
function display()
{
echo $this->name;
}
}
$obj1=new test1();
$obj1->get("nithi");
echo "<b>serialization<br></b>";
$str=serialize($obj1);
echo $str;
echo "<b><br>Unserialization</b>";
$obj2 = unserialize($str);
echo "<br>";
$obj2->display();
?>
Program 2:
<?php
class createserialize
{
public $a,$b;
public function __construct($s,$p)
{
$this->a = $s;
$this->b = $p;
}
public function display ()
{
echo $this->a;
echo $this->b;
}
}
$obj1 = new createserialize(10,20);
echo "<b>Serialization<br></b>";
$str = serialize($obj1);
echo $str;
echo "<b><br>Unserialization<br></b>";
$obj2 = unserialize($str);
$obj2->display();
?>
Sleep and wakeup
● __sleep and __wakeup are methods that are related to the serialization process.
● Serialize function checks if a class has a __sleep method.
○ If so, it will be executed before any serialization. __sleep is supposed to return
an array of the names of all variables of an object that should be serialized.
● __wakeup in turn will be executed by unserialize if it is present in class.
○ It's intention is to re-establish resources and other things that are needed to
be initialized upon unserialization.
Program 1:
<?php
class serializedemo
{
public $message, $message1;
public function __construct($statement)
{
$this->message = $statement;
$this->message1= $this->message."Again";
}
public function __sleep() {
return array('message');
}
public function __wakeup() {
$this->message1 =$this->message . "Again!";
}
public function display ()
{
echo $this->message1;
}
}
$obj1 =new serializedemo("Welocme you!");
$serialization = serialize($obj1);
$obj2 = unserialize($serialization);
$obj2->display();
?>
Introspection Functions
● Introspection in PHP offers the useful ability to examine an object's
characteristics, such as its name, parent class (if any) properties,
classes, interfaces, and methods.
● PHP offers a large number of functions that you can use to accomplish
the task.
These functions break down into the following four broad categories:
● Getting information about the class hierarchy
● Finding out about member variables
● Finding out about member functions
● Actually calling member functions
Program 1:
<?php
class Example
{
public $var1 = "initialized";
public $var2 = "initialized";
public $var3;
public $var4;
public function __construct()
{
$this->var3 = "set";
$this->var1 = "changed";
}
}
$example = new Example();
print_r(get_class_vars("Example"));
echo "<br>";
print_r(get_object_vars($example));
?>
Example 1:Class genealogy
<?php
class UIElement {}
class Control extends UIelement {}
class Widget extends Control { }
class Button extends Widget {}
class Clicker extends Button {}
function ancestry($class_name)
{
echo $class_name;
if ($parent = get_parent_class($class_name))
{
print(" => ");
ancestry($parent);
}
}
echo "Class ancestry:”;
ancestry("Clicker");
?>
OOP Style in PHP
● Naming conventions
● Accessor functions
1.Naming conventions
● we simply pass along the parts of the PEAR coding style that pertain to objects
● PEAR is short for "PHP Extension and Application Repository"
● PEAR recommends that class names begin with an uppercase letter and have that inclusion
path in the class name, separated by underscores
● If your class that counts words, and which belongs to a PEAR package called TextUtils, might
be called TextUtils_WordCounter.
● Member variables and member function names should have their first real letter be lowercase
and have word boundaries be delineated by capitalization.
● In addition, names that are intended to be private to the class should start with an
2.Accessor functions
● Another style of documenting your intent about use of internal variables is to have your
variables marked as private, in general, and
● It provides “getter” and “setter” functions to outside callers.
Example 1:
<?php
class Customer
{
private $_name;
private $_rating;
function getName ()
{
$this->_name="nithi";
return($this->_name);
}
function getRating ()
{
return($this->_rating);
}
function setRating($rating)
{
$this->_rating = $rating;
}
}
$obj1 = new Customer();
echo $obj1->getName();
$obj1->setRating(4);
echo $obj1->getRating();
?>

More Related Content

Similar to UNIT III (8).pptx

PHP OOP Lecture - 03.pptx
PHP OOP Lecture - 03.pptxPHP OOP Lecture - 03.pptx
PHP OOP Lecture - 03.pptxAtikur Rahman
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3Toni Kolev
 
Advanced php
Advanced phpAdvanced php
Advanced phphamfu
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpAlena Holligan
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHPMichael Peacock
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPsRavi Bhadauria
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Alena Holligan
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingIqra khalil
 
Migration from Procedural to OOP
Migration from Procedural to OOP Migration from Procedural to OOP
Migration from Procedural to OOP GLC Networks
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Alena Holligan
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptxrani marri
 
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Alena Holligan
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classesKumar
 

Similar to UNIT III (8).pptx (20)

PHP OOP Lecture - 03.pptx
PHP OOP Lecture - 03.pptxPHP OOP Lecture - 03.pptx
PHP OOP Lecture - 03.pptx
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
 
Advanced php
Advanced phpAdvanced php
Advanced php
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphp
 
Oops concept in php
Oops concept in phpOops concept in php
Oops concept in php
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
Php oop (1)
Php oop (1)Php oop (1)
Php oop (1)
 
Demystifying oop
Demystifying oopDemystifying oop
Demystifying oop
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Migration from Procedural to OOP
Migration from Procedural to OOP Migration from Procedural to OOP
Migration from Procedural to OOP
 
Oops in php
Oops in phpOops in php
Oops in php
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
 
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classes
 
Python advance
Python advancePython advance
Python advance
 

More from DrDhivyaaCRAssistant (15)

UNIT 1 (8).pptx
UNIT 1 (8).pptxUNIT 1 (8).pptx
UNIT 1 (8).pptx
 
Unit – II (1).pptx
Unit – II (1).pptxUnit – II (1).pptx
Unit – II (1).pptx
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
 
UNIT I (6).pptx
UNIT I (6).pptxUNIT I (6).pptx
UNIT I (6).pptx
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
 

Recently uploaded

Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 

UNIT III (8).pptx

  • 2. Contents Object Oriented Programming – Basics PHP constructs for OOP – Advanced OOP features – Introspection Functions – OOP Style in PHP
  • 3. Object Oriented Programming ● OOP stands for Object-Oriented Programming. ● 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. Object-oriented programming has several advantages over procedural programming: ● OOP is faster and easier to execute ● OOP provides a clear structure for the programs ● OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug ● OOP makes it possible to create full reusable applications with less code and shorter development time
  • 4. The object-oriented approach(Terminology) ● Class: This is a programmer-defined data type, which includes local functions as well as local data. ● Object: (Also known as object instance, or instance.) ○ An individual instance of the data structure defined by a class. ○ You define a class once and then make many objects that belong to it. ● Member variable: (Also known as property, attribute, or instance variable.) One of the component pieces of data in a class definition. ● Member function: (Also known as method.) A member that happens to be a function.
  • 5. ● Inheritance: ○ The process of defining a class in terms of another class. ○ The new (child) class has all the member data and member function definitions from the old (parent) class by default but may define new members or “override” parent functions and give them new definitions. ○ We say that class A inherits from class B if class A is defined in terms of class B in this way. ○ Parent class (or superclass or base class): A class that is inherited from by another class. ○ Child class (or subclass or derived class): A class that inherits from another class.
  • 6. Single inheritance ● PHP allows a class definition to inherit from another class, using the extends clause. Both member variables and member functions are inherited. Multiple inheritance ● PHP offers no support for multiple inheritance as in Java. Each class inherits from, at most, one parent class (though a class may implement many interfaces). Encapsulation − refers to a concept where we encapsulate all the data and member functions together to form an object. ○ It is also known as information hiding concept Constructor − refers to a special type of function which will be called automatically whenever there is an object formation from a class. Destructor − refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope.
  • 7. Basic PHP Constructs for OOP Defining classes class myclass { public $var1; public $var2 ; public function myfunc ($arg1, $arg2) { …….. } }
  • 8. The form of the syntax is as described, in order, in the following list: ● The special form class, followed by the name of the class that you want to define. ● A set of braces enclosing any number of variable declarations and function definitions. ● Variable declarations start with the special form public, private, or protected, which is followed by a conventional $ variable name; they may also have an initial assignment to a constant value.
  • 9. Creating instances After we have a class definition, the default way to make an instance of that class is by using the new operator Example: objectname = new classname; $box = new TextBoxSimple; $box->display(); Accessing member variables In general, the way to refer to a member variable from an object is to follow a variable containing the object with -> and then the name of the member Example : $variablename =object->member variable $textbox = $box->body_text;
  • 10. Example: <?php class Fruit { // Properties public $name; // Methods function set_name($name) { $this->name = $name; } function get_name() { return $this->name; } } $apple = new Fruit();// object creation $apple->set_name('Apple'); echo $apple->get_name(); ?>
  • 11. After we have a class definition, the default way to make an instance of that class is by using the new operator Example: objectname = new classname; $box = new TextBoxSimple; $box->display(); In general, the way to refer to a member variable from an object is to follow a variable containing the object with -> and then the name of the member Example : $variablename =object->member variable $textbox = $box->body_text;
  • 12. Constructor functions ● A constructor allows you to initialize an object's properties upon creation of the object. ● The correct way to arrange for data to be appropriately initialized is by writing a constructor function — a special function called __construct(), which will be called automatically whenever a new instance is created. ● The construct function starts with two underscores (__)
  • 13. Example 1 <?php class text { public $a; function __construct($a)// constructor { $this->a = $a; } function display() { echo $this->a; } } $text1= new text("hello"); $text1->display(); ?>
  • 14.
  • 15. Example 2 <?php class student { public $id; public $name; function __construct($id,$name) { $this->id = $id; $this->name = $name; } function display1() { echo $this->id; } function display2() { echo $this->name; }} $s1= new student(2,"arun"); echo "<center>"; echo "<table border='1'>"; echo "<th>id</th><th>name</th>"; echo "<tr><td>"; $s1->display1(); echo "<td>"; $s1->display2(); echo "</td></tr>"; echo "</center>"; ?>
  • 16. Destructor functions ● A destructor is called when the object is destructed or the script is stopped or exited. ● The destruct() function will be called automatically at the end of the script. ● The destruct function starts with two underscores(__) <?php class text { public $a; function __construct($a)// constructor { $this->a = $a; } function __destruct() { echo $this->a; } } $text1= new text("hello"); ?>
  • 17. Inheritance ● Inheritance in OOP = When a class derives from another class. ● The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods. ● An inherited class is defined by using the extends keyword. ● PHP class definitions can optionally inherit from a parent class definition by using the extends clause. ● The syntax is: class Child extends Parent { <definition body> }
  • 18. The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics: ● Automatically has all the member variable declarations of the parent class (or superclass or base class) ● Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent
  • 19. Example: <?php class student { public $name; public $mark1; public $mark2; public function __construct($name, $mark1,$mark2) { $this->name = $name; $this->mark1 = $mark1; $this->mark2 = $mark2; } public function display() { echo "name=".$this->name."<br>"; echo "mark1=".$this->mark1."<br>"; echo "mark2=".$this->mark2."<br>";} } class addition extends student { public $total; public function add() { $total=$this->mark1+$this- >mark2; echo "total=".$total;; } } $s1 = new addition("Abi",50,60); $s1->display(); $s1->add(); ?>
  • 20.
  • 21. Chained subclassing ● PHP does not support multiple inheritance but does support chained subclassing. ● This is a fancy way of saying that, although each class can have only a single parent, classes can still have a long and distinguished ancestry (grandparents, great- grandparents, and so on). (multilvel) ● Also, there’s no restriction on family size; ● each parent class can have an arbitrary number of children. (Hierarchical)
  • 22.
  • 23. Example1:(multilevel inheritance) <?php class student { public $name; public $m1; public $m2; public function get() { $this->name = "arun"; $this->m1 =60; $this->m2 =70; } public function display() { echo "name=".$this->name."<br>"; echo "mark1=".$this->m1."<br>"; echo "mark2=".$this->m2."<br>";
  • 24. class total extends student { public $total; public function computeTotal() { $this->total= $this->m1+$this->m2; echo "total=".$this->total."<br>"; } } class avg extends total { public $avg; public function calculateAvg() { $this->avg=$this->total= $this->total/2; echo "avg=".$this->avg; } } $avg1 = new avg(); $avg1->get(); $avg1->display(); $avg1->computeTotal(); $avg1->calculateAvg(); ?>
  • 25. Example2:(Hierarchical inheritance) <?php class arith{ public $m1; public $m2; public function get() { $this->m1 =60; $this->m2 =70; } public function display() { echo "number1=".$this->m1."<br>"; echo "number2=".$this->m2."<br>"; } } class addition extends arith { public $add; public function computeadd() { $this->add= $this->m1+$this->m2; echo "add=".$this->add."<br>"; } }
  • 26. class subtraction extends arith { public $sub; public function calculatesub() { $this->sub=$this->m1-$this->m2; echo "sub=".$this->sub; } } $a1=new addition(); $s1=new subtraction(); $a1->get(); $a1->display(); $a1->computeadd(); $s1->get(); $s1->calculatesub(); ?>
  • 27. Overriding method (functions) ● Method overriding allows a child class to provide a specific implementation of a method already provided by its parent class. ● Method overriding occurs when a subclass (child class) has the same method as the parent class ● To override a method, you redefine that method in the child class with the same name, parameters, and return type. ● The method in the parent class is called overridden method, ● while the method in the child class is known as the overriding method. ● The code in the overriding method overrides (or replaces) the code in the overridden method.
  • 28. PHP will decide which method (overridden or overriding method) to call based on the object used to invoke the method. ● If an object of the parent class invokes the method, PHP will execute the overridden method. ● But if an object of the child class invokes the method, PHP will execute the overriding method.
  • 29. Example: <?php class base{ public function display() { echo "parent method"; } } class sub extends base { public function display() { echo "child method"; } } $sub1=new sub(); $sub1->display(); ?>
  • 30. Scoping issues ● Names of member variables and member functions are never meaningful to calling code on their own , they must always be reached via the -> construct ● The names visible within member functions are exactly the same as the names visible within global functions — that is, member functions can refer freely to other global functions but can’t refer to normal global variables unless those variables have been declared global inside the member function definition.
  • 31. Advanced OOP features 1.Public, Private, and Protected Members Public:(default access speicifier) Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations: ● The property or method can be accessed from everywhere. This is default ○ From outside the class in which it is declared ○ From within the class in which it is declared ○ From within another class that implements the class in which it is declared
  • 32. Example: <?php class student { var $name;// default access specifier public public $mark1,$mark2; function get($name, $mark1,$mark2) { $this->name = $name; $this->mark1 = $mark1; $this->mark2 = $mark2; } function display() { echo "name=".$this->name."<br>"; echo "mark1=".$this->mark1."<br>"; echo "mark2=".$this->mark2."<br>";} } $s1 = new student(); $s1->get("nithya",50,60); $s1->display(); ?>
  • 33. Private: ● The property or method can ONLY be accessed within the class ● The private member cannot be referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class. Protected: ● The property or method can be accessed within the class and by classes derived from that class ● A protected property or method is accessible in the class in which it is declared, as well as in classes that extend that class
  • 34. Example: <?php class student { protected $name; protected $mark1,$mark2; function get($name, $mark1,$mark2) { $this->name = $name; $this->mark1 = $mark1; $this->mark2 = $mark2; } function display() { echo "name=".$this->name."<br>"; echo "mark1=".$this->mark1."<br>"; echo "mark2=".$this->mark2."<br>";} } class addition extends student { function add() { $total=$this->mark1+$this->mark2; echo "total=".$total;; }} $s1 = new addition(); $s1->get("nithi",50,60); $s1->display(); $s1->add(); ?>
  • 35. 2.Interfaces ● Interfaces allow you to specify what methods a class should implement. ● An interface consists of methods that have no implementations, which means the interface methods are abstract methods. ● All the methods in interfaces must have public visibility scope. ● Interfaces are different from classes as the class can inherit from one class only whereas the class can implement one or more interfaces.
  • 36. Example: interface Mail { public function sendMail(); } class Report implements Mail { // Definition goes here }
  • 37. Program: <?php interface Arithmetic { public function add(); } class Addition implements Arithmetic { var $p,$q; public function add() { $this->p=50; $this->q=40; $this->sum=$this->p+$this->q; echo "add=".$this->sum; } } $obj1 = new Addition(); $obj1->add(); ?>
  • 38. 3.Constants ● A constant is somewhat like a variable, in that it holds a value but is really more like a function because a constant is immutable. Once you declare a constant, it does not change. ● The constant’s name does not have a leading $, as variable names do. ● Constants cannot be changed once it is declared. ● Class constants can be useful if you need to define some constant data within a class. ● A class constant is declared inside a class with the const keyword. ● We can access a constant from outside the class by using the class name followed by the scope resolution operator (::) followed by the constant name ● we can access a constant from inside the class by using the self keyword followed by the scope resolution operator (::)
  • 39. Program: <?php class area { const pi=3.14; // const value var $r,$a; function get($r) { $this->r = $r; } function compute() { $this->a= self::pi*$this->r*$this->r; echo "area of circle=".$this->a; } } $area1 = new area(); $area1->get(6); $area1->compute(); ?>
  • 40. 4.Abstract classes ● An abstract class is one that cannot be instantiated, only inherited. ● An abstract class is a class that contains at least one abstract method. ● An abstract method is a method that is declared, but not implemented in the code. ● An abstract class or method is defined with the abstract keyword abstract class MyAbstractClass { abstract function myAbstractFunction() { } }
  • 41. Program: <?php abstract class rect { var $l,$b,$a; function get() { $this->l=6; $this->b=5; } abstract function compute(); } class area extends rect { function compute() { $this->a=$this->l*$this->b; echo "area of rect =".$this->a; } } $area1 = new area(); $area1->get(); $area1->compute();
  • 42. 5.Simulating class functions ● In PHP, there are no declarations in a class definition that indicate whether a function is intended for per-instance or per-class use. ● But PHP does offer a syntax for getting to functions in a class even when no instance is handy. ● The :: syntax operates much like the -> syntax does, except that it joins class names to member functions rather than instances to members
  • 43. Program: <?php class calculator { var $a,$b,$c; function compute() { $a=6; $b=6; $c=$a+$b; echo "add=".$c; } } calculator::compute(); ?>
  • 44. 6.Calling parent functions Calling parent constructors ● To call the constructor of the parent class from the constructor of the child class, use following syntax ○ parent::__construct(arguments) Automatic calls to parent constructors if a subclass lacks a constructor function(not having constructor) and a superclass has one, the superclass’s constructor will be invoked
  • 45. Program: <?php class student { protected $name; protected $m1; protected $m2; public function __construct($name) { $this->name = $name; } } class details extends student { public function __construct($name,$m1,$m2) { student::__construct($name); // call to parent constructor $this->m1=$m1; $this->m2=$m2; } public function compute() { echo $this->name; echo "<br>"; $total= $this->m1+$this->m2; echo $total; } } $d= new details("nithi",60,70); $d->compute(); ?>
  • 46. 7.Simulating method overloading ● Method overloading contains same function name and that function performs different task according to number of arguments ● In PHP overloading means the behavior of method changes dynamically according to the input parameter. ● The __call() method is invoked automatically when a non-existing method or inaccessible method is called. The following shows the syntax of the __call() method: ○ public __call ( string $name , array $arguments ) ● The __call() method accepts two arguments: ● $name is the name of the method that is being called by the object. ● $arguments is an array of arguments passed to the method call.
  • 47. Program: <?php class Shape { const PI = 3.142 ; function __call($name,$arg) { $count=count($arg); if($count==1) { $c= self::PI*$arg[0]; echo "area of circle=".$c; } elseif($count==2) { $c= $arg[0]*$arg[1]; echo "area of rect=".$c; } } } $s = new Shape(); $s->area(8,6); echo "<br>"; $s->area(3); ?>
  • 48. 8.Serialization ● Serialization of data means converting it into a string of bytes in such a way that you can produce the original data again from the string (via a process known, unsurprisingly, as unserialization). ● PHP provides a mechanism for storing and loading data with PHP types across multiple HTTP requests. ● This mechanism boils down to two functions: serialize() and unserialize(). Serialization ● A string representation of any object in the form of byte-stream is obtained by serialize() function in PHP ● All property variables of object are contained in the string and methods are not saved. This string can be stored in any file Deserialization ● To retrieve the object from the byte stream, there is unserialize() function
  • 49. Sample serialization output O:8:"stdClass":1:{s:4:"data";s:10:"Some data!";} ● The O stands for the type of the serialized string. In this case the O maps to a PHP object. ● The 8 seperated by the colons represents the length of the name of the class ● The following 1 represents the number of properties the serialized object contains which are stored within curly brackets ● Each property is stored as a serialized string representing the property name, a semicolon and a serialized string representing the value.
  • 50. Program 1: <?php class test1 { public $name; function get($arg){ $this->name=$arg; } function display() { echo $this->name; } } $obj1=new test1(); $obj1->get("nithi"); echo "<b>serialization<br></b>"; $str=serialize($obj1); echo $str; echo "<b><br>Unserialization</b>"; $obj2 = unserialize($str); echo "<br>"; $obj2->display(); ?>
  • 51. Program 2: <?php class createserialize { public $a,$b; public function __construct($s,$p) { $this->a = $s; $this->b = $p; } public function display () { echo $this->a; echo $this->b; } } $obj1 = new createserialize(10,20); echo "<b>Serialization<br></b>"; $str = serialize($obj1); echo $str; echo "<b><br>Unserialization<br></b>"; $obj2 = unserialize($str); $obj2->display(); ?>
  • 52. Sleep and wakeup ● __sleep and __wakeup are methods that are related to the serialization process. ● Serialize function checks if a class has a __sleep method. ○ If so, it will be executed before any serialization. __sleep is supposed to return an array of the names of all variables of an object that should be serialized. ● __wakeup in turn will be executed by unserialize if it is present in class. ○ It's intention is to re-establish resources and other things that are needed to be initialized upon unserialization.
  • 53. Program 1: <?php class serializedemo { public $message, $message1; public function __construct($statement) { $this->message = $statement; $this->message1= $this->message."Again"; } public function __sleep() { return array('message'); } public function __wakeup() { $this->message1 =$this->message . "Again!"; } public function display () { echo $this->message1; } } $obj1 =new serializedemo("Welocme you!"); $serialization = serialize($obj1); $obj2 = unserialize($serialization); $obj2->display(); ?>
  • 54. Introspection Functions ● Introspection in PHP offers the useful ability to examine an object's characteristics, such as its name, parent class (if any) properties, classes, interfaces, and methods. ● PHP offers a large number of functions that you can use to accomplish the task.
  • 55.
  • 56.
  • 57. These functions break down into the following four broad categories: ● Getting information about the class hierarchy ● Finding out about member variables ● Finding out about member functions ● Actually calling member functions
  • 58. Program 1: <?php class Example { public $var1 = "initialized"; public $var2 = "initialized"; public $var3; public $var4; public function __construct() { $this->var3 = "set"; $this->var1 = "changed"; } } $example = new Example(); print_r(get_class_vars("Example")); echo "<br>"; print_r(get_object_vars($example)); ?>
  • 59. Example 1:Class genealogy <?php class UIElement {} class Control extends UIelement {} class Widget extends Control { } class Button extends Widget {} class Clicker extends Button {} function ancestry($class_name) { echo $class_name; if ($parent = get_parent_class($class_name)) { print(" => "); ancestry($parent); } } echo "Class ancestry:”; ancestry("Clicker"); ?>
  • 60. OOP Style in PHP ● Naming conventions ● Accessor functions
  • 61. 1.Naming conventions ● we simply pass along the parts of the PEAR coding style that pertain to objects ● PEAR is short for "PHP Extension and Application Repository" ● PEAR recommends that class names begin with an uppercase letter and have that inclusion path in the class name, separated by underscores ● If your class that counts words, and which belongs to a PEAR package called TextUtils, might be called TextUtils_WordCounter. ● Member variables and member function names should have their first real letter be lowercase and have word boundaries be delineated by capitalization. ● In addition, names that are intended to be private to the class should start with an
  • 62. 2.Accessor functions ● Another style of documenting your intent about use of internal variables is to have your variables marked as private, in general, and ● It provides “getter” and “setter” functions to outside callers.
  • 63. Example 1: <?php class Customer { private $_name; private $_rating; function getName () { $this->_name="nithi"; return($this->_name); } function getRating () { return($this->_rating); } function setRating($rating) { $this->_rating = $rating; } } $obj1 = new Customer(); echo $obj1->getName(); $obj1->setRating(4); echo $obj1->getRating(); ?>