SlideShare a Scribd company logo
1 of 41
PHP-II
Why use classes and objects?
• PHP is a primarily procedural language
• small programs are easily written without
adding any classes or objects
• larger programs, however, become cluttered
with so many disorganized functions
• grouping related data and behavior into
objects helps manage size and complexity
CS380 2
OOP with PHP
why OOP in PHP
Common OOP approach advantages
• Modularity
• Less code
• Reusability
• Robustness
• Handling large projects, easy to maintain
• Classes usually reflect database schema
• PHP is not inherently OOP language!
OOP with PHP
why OOP in PHP – examples
• Online shops
• Banking systems
• News services
• Editors' systems
• Home pages
• => use OOP to separate the functionality
from layout
OOP with PHP
characteristics
• PHP fulfills:
– Abstract data types
– Information hiding
– Inheritance
– Polymorphism
• Object-oriented programming (OOP) refers to the
creation of reusable software object-types / classes that
can be efficiently developed and easily incorporated into
multiple programs.
• In OOP an object represents an entity in the real world
(a student, a desk, a button, a file, a text input area, a
loan, a web page, a shopping cart).
• An OOP program = a collection of objects that interact to
solve a task / problem.
Object-Oriented Programming
6
• Classes are constructs that define objects of the same type.
A class is a template or blueprint that defines what an
object’s data and methods will be.
Objects of a class have:
– Same operations, behaving the same way
– Same attributes representing the same features, but
values of those attributes (= state) can vary from object to
object
• An object is an instance of a class.
(terms objects and instances are used interchangeably)
• Any number of instances of a class can be created.
Object-Oriented Programming
7
8
Example: A “Rabbit” object
• You could (in a game, for example) create an
object representing a rabbit
• It would have data:
– How hungry it is
– How frightened it is
– Where it is
• And methods:
– eat, hide, run, dig
Constructing and using objects
9
# construct an object
$name = new ClassName(parameters);
# access an object's field (if the field is public)
$name->fieldName
# call an object's method
$name->methodName(parameters);
PHP
• the above code unzips a file
• test whether a class is installed with class_exists
CS380
$zip = new ZipArchive();
$zip->open("moviefiles.zip");
$zip->extractTo("images/");
$zip->close(); PHP
PHP Class
• A class can contain it’s own constants, variables (called
“Properties”) and functions (calles “methods”).
Class declaration syntax
11
class ClassName {
# fields - data inside each object
public $name; # public field
private $name; # private field
# constructor - initializes each object's
state
public function __construct(parameters) {
statement(s);
}
# method - behavior of each object
public function name(parameters) {
statements;
}
} PHP
• inside a constructor or method, refer to the current object as
$this
Class example
12
<?php
class Point {
public $x;
public $y;
# equivalent of a Java constructor
public function __construct($x, $y) {
$this->x = $x;
$this->y = $y;
}
public function distance($p) {
$dx = $this->x - $p->x;
$dy = $this->y - $p->y;
return sqrt($dx * $dx + $dy * $dy);
}
# equivalent of Java's toString method
public function __toString() {
return "(" . $this->x . ", " . $this->y .
")";
}
} ?> PHP
13
Example of a class
class Employee {
// Fields
private String name; //Can get but not change
private double salary; // Cannot get or set
// Constructor
Employee(String n, double s) {
name = n; salary = s;
}
// Methods
void pay () {
System.out.println("Pay to the order of " +
name + " $" + salary);
}
public String getName() { return name; } // getter
}
• Destructor = opposite of constructor
– Allows some functionality that will be automatically
executed just before an object is destroyed
An object is removed when there is no reference
variable/handle left to it
Usually during the "script shutdown phase", which is typically
right before the execution of the PHP script finishes
– A default destructor provided by the compiler only if a
destructor function is not explicitly declared in the class
Creating Classes in PHP
14
Constructors
• All objects can have a special built-in method called a
'constructor'. Constructors allow you to initialize your object's
properties (translation: give your properties values,) when
you instantiate (create) an object.
Destructor
• <?php
class MyDestructableClass {
function __construct() {
print "In constructorn";
$this->name = "MyDestructableClass";
}
function __destruct() {
print "Destroying " . $this->name . "n";
}
}
$obj = new MyDestructableClass();
?>
 Once a class has been created, any number of object instances of
that class can be created.
 $dogRobot = new Robot();
 To invoke methods:
 object->method()
Instantiating Classes
17
 e.g.
<?php
....
$dogRobot = new Robot();
$dogRobot ->crawlWeb();
$dogRobot -> play();
echo $dogRobot ->talk();
... ?>
• From operations within the class, class’s data /
methods can be accessed / called by using:
– $this = a variable that refers to the current instance of the class, and can
be used only in the definition of the class.
– The pointer operator -> (similar to Java’s object member access operator “.” )
– class Test {
public $attribute;
function f ($val) {
$this -> attribute = $val; // $this is mandatory!
} // if omitted, $attribute is treated
} // as a local var in the function
Using Data/Method Members
18
• From outside the class, accessible (as determined by access
modifiers) data and methods are accessed through a variable
holding an instance of the class, by using the same pointer operator.
class Test {
public $attribute;
}
$t = new Test();
$t->attribute = “value”;
echo $t->attribute;
Using Data/Method Members
19
 Visibility of a method or data member:
 Public
 Protected
 Private
By default, without the access specifies, class members
are defined public.
Defining and Using Variables, Constants
and Functions
20
• Class members declared public can be
accessed everywhere.
• Members declared protected can be accessed
only within the class itself and by inherited
classes
• Members declared as private may only be
accessed by the class that defines the
member.
Encapsulation
• Data members are normally set inaccessible
from outside the class (as well as certain types
of methods) protecting them from the rest of
the script and other classes.
• This protection of class members is known as
encapsulation.
Encapsulation
• <?php
class App {
private static $_user;
public function User( ) {
if( $this->_user == null )
{
$this->_user = new User();
}
return $this->_user;
} }
?>
Getter and setter functions
Inheritance in PHP
• Inheritance is a concept in object oriented programming. With
the help of inheritance we can get all property and method of
one class in another class. This is principle to take re-
fusibility on upper level. Inheritance in php is introduced
from php5 version.
Inheritance
• New classes can be defined very similar to existing ones. All
we need to do is specify the differences between the new
class and the existing one.
• Data members and methods which are not defined as being
private to a class are automatically accessible by the new
class.
• This is known as inheritance and is an extremely powerful
and useful programming tool.
Inheritance
• class Animal {
public $name;
public function Greet()
{
return "Hello, I'm some sort of animal and my
name is " . $this->name; }
}
Inheritance
class Dog extends Animal {
public function Greet()
{ return "Hello, I'm a dog and my name is " .
$this->name; }
}
Inheritance
Overriding methods
• Sometimes (when using inheritance,) you may need to change
how a method works from the base class.
• For example, let's say set_name() method in the 'employee'
class, had to do something different than what it does in the
'person' class.
• You 'override' the 'person' classes version of set_name(), by
declaring the same method in 'employee'.
Overriding methods
OOP with PHP
Overloading in PHP
<?php
class ShoppingCart{
function ShoppingCart(){
$to_call="ShoppingCart".func_num_args();
$args = func_get_args(); // return an array of arguments
$args = implode(':',$args);
$args = str_replace(“:”, “,”, $args);
$run = “$this->$to_call ($args);”; // variable variable
eval ($run);
}
function ShoppingCart1($x=”2”) { code1();}
function ShoppingCart2($x=”2”,$y=”3”) { code2();}
}
?>
OOP with PHP
Polymorphism
• All class member functions are virtual by
the definition
class A {
function draw() { echo "1"; } // not needed
function boo() { $this->draw(); }
}
class B extends A {
function draw() { echo "drawing B"; }
}
$b = new B();
$b->boo(); // outputs “drawing B”
what is abstract class in php?
• An abstract class is a class that contains at least one abstract
method, which is a method without any actual code in it, just
the name and the parameters, and that has been marked as
"abstract".
• The purpose of this is to provide a kind of template to inherit
from and to force the inheriting class to implement the
abstract methods.
• An abstract class thus is something between a regular class
and a pure interface. Also interfaces are a special case of
abstract classes where ALL methods are abstract.
Abstract class in php
PHP Interfaces
• interfaces exist not as a base on which classes can extend but
as a map of required functions.
• The entire point of interfaces is to give you the flexibility to
have your class be forced to implement multiple interfaces,
but still not allow multiple inheritance. The issues with
inheriting from multiple classes
PHP Interfaces
Differences between abstract class and
interface in PHP
• In abstract classes this is not necessary that every method
should be abstract. But in interface every method is abstract.
• Multiple and multilevel both type of inheritance is possible in
interface. But single and multilevel inheritance is possible in
abstract classes.
• Method of php interface must be public only. Method in
abstract class in php could be public or protected both.
• In abstract class you can define as well as declare methods.
But in interface you can only defined your methods.
Object example: Fetch file from web
39
# create an HTTP request to fetch student.php
$req = new HttpRequest("student.php",
HttpRequest::METH_GET);
$params = array("first_name" => $fname, "last_name"
=> $lname);
$req->addPostFields($params);
# send request and examine result
$req->send();
$http_result_code = $req->getResponseCode(); # 200
means OK
print "$http_result_coden";
print $req->getResponseBody();
PHP
• PHP's HttpRequest object can fetch a document from the
web
CS380
OOP with PHP
Generic function for setting the member
variables
function Set ($varname, $value) {
$this->$varname = $value;
}
$instance->Set ('size','5');
OOP with PHP
Serializing the objects
• Partially overcomes the need for a persistent
object
• !!Saves only data members, not methods!
(PHP4 is exception)
<?php
$myCart = new ShoppingCart();
$stream1 = serialize($myCart); // and store to file or db
...
... // retreive from file/db after a year..
$myLaterCart = unserialize($stream1);
?>
• Not recommended to use!

More Related Content

Similar to PHP OOP: Why Use Classes and Objects in 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 #pnwphpAlena Holligan
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Alena Holligan
 
Advanced php
Advanced phpAdvanced php
Advanced phphamfu
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.Tarunsingh198
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPsRavi Bhadauria
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in phpCPD INDIA
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
Intro to OOP PHP and Github
Intro to OOP PHP and GithubIntro to OOP PHP and Github
Intro to OOP PHP and GithubJo Erik San Jose
 
Object_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdfObject_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdfGammingWorld2
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oopcolleges
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHPRohan Sharma
 

Similar to PHP OOP: Why Use Classes and Objects in PHP (20)

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
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
 
PHP- Introduction to Object Oriented PHP
PHP-  Introduction to Object Oriented PHPPHP-  Introduction to Object Oriented PHP
PHP- Introduction to Object Oriented PHP
 
Advanced php
Advanced phpAdvanced php
Advanced php
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
OOPS Characteristics
OOPS CharacteristicsOOPS Characteristics
OOPS Characteristics
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
Oopsinphp
OopsinphpOopsinphp
Oopsinphp
 
Intro to OOP PHP and Github
Intro to OOP PHP and GithubIntro to OOP PHP and Github
Intro to OOP PHP and Github
 
Object_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdfObject_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdf
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oop
 
Oops in php
Oops in phpOops in php
Oops in php
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHP
 

Recently uploaded

HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 

Recently uploaded (20)

HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 

PHP OOP: Why Use Classes and Objects in PHP

  • 2. Why use classes and objects? • PHP is a primarily procedural language • small programs are easily written without adding any classes or objects • larger programs, however, become cluttered with so many disorganized functions • grouping related data and behavior into objects helps manage size and complexity CS380 2
  • 3. OOP with PHP why OOP in PHP Common OOP approach advantages • Modularity • Less code • Reusability • Robustness • Handling large projects, easy to maintain • Classes usually reflect database schema • PHP is not inherently OOP language!
  • 4. OOP with PHP why OOP in PHP – examples • Online shops • Banking systems • News services • Editors' systems • Home pages • => use OOP to separate the functionality from layout
  • 5. OOP with PHP characteristics • PHP fulfills: – Abstract data types – Information hiding – Inheritance – Polymorphism
  • 6. • Object-oriented programming (OOP) refers to the creation of reusable software object-types / classes that can be efficiently developed and easily incorporated into multiple programs. • In OOP an object represents an entity in the real world (a student, a desk, a button, a file, a text input area, a loan, a web page, a shopping cart). • An OOP program = a collection of objects that interact to solve a task / problem. Object-Oriented Programming 6
  • 7. • Classes are constructs that define objects of the same type. A class is a template or blueprint that defines what an object’s data and methods will be. Objects of a class have: – Same operations, behaving the same way – Same attributes representing the same features, but values of those attributes (= state) can vary from object to object • An object is an instance of a class. (terms objects and instances are used interchangeably) • Any number of instances of a class can be created. Object-Oriented Programming 7
  • 8. 8 Example: A “Rabbit” object • You could (in a game, for example) create an object representing a rabbit • It would have data: – How hungry it is – How frightened it is – Where it is • And methods: – eat, hide, run, dig
  • 9. Constructing and using objects 9 # construct an object $name = new ClassName(parameters); # access an object's field (if the field is public) $name->fieldName # call an object's method $name->methodName(parameters); PHP • the above code unzips a file • test whether a class is installed with class_exists CS380 $zip = new ZipArchive(); $zip->open("moviefiles.zip"); $zip->extractTo("images/"); $zip->close(); PHP
  • 10. PHP Class • A class can contain it’s own constants, variables (called “Properties”) and functions (calles “methods”).
  • 11. Class declaration syntax 11 class ClassName { # fields - data inside each object public $name; # public field private $name; # private field # constructor - initializes each object's state public function __construct(parameters) { statement(s); } # method - behavior of each object public function name(parameters) { statements; } } PHP • inside a constructor or method, refer to the current object as $this
  • 12. Class example 12 <?php class Point { public $x; public $y; # equivalent of a Java constructor public function __construct($x, $y) { $this->x = $x; $this->y = $y; } public function distance($p) { $dx = $this->x - $p->x; $dy = $this->y - $p->y; return sqrt($dx * $dx + $dy * $dy); } # equivalent of Java's toString method public function __toString() { return "(" . $this->x . ", " . $this->y . ")"; } } ?> PHP
  • 13. 13 Example of a class class Employee { // Fields private String name; //Can get but not change private double salary; // Cannot get or set // Constructor Employee(String n, double s) { name = n; salary = s; } // Methods void pay () { System.out.println("Pay to the order of " + name + " $" + salary); } public String getName() { return name; } // getter }
  • 14. • Destructor = opposite of constructor – Allows some functionality that will be automatically executed just before an object is destroyed An object is removed when there is no reference variable/handle left to it Usually during the "script shutdown phase", which is typically right before the execution of the PHP script finishes – A default destructor provided by the compiler only if a destructor function is not explicitly declared in the class Creating Classes in PHP 14
  • 15. Constructors • All objects can have a special built-in method called a 'constructor'. Constructors allow you to initialize your object's properties (translation: give your properties values,) when you instantiate (create) an object.
  • 16. Destructor • <?php class MyDestructableClass { function __construct() { print "In constructorn"; $this->name = "MyDestructableClass"; } function __destruct() { print "Destroying " . $this->name . "n"; } } $obj = new MyDestructableClass(); ?>
  • 17.  Once a class has been created, any number of object instances of that class can be created.  $dogRobot = new Robot();  To invoke methods:  object->method() Instantiating Classes 17  e.g. <?php .... $dogRobot = new Robot(); $dogRobot ->crawlWeb(); $dogRobot -> play(); echo $dogRobot ->talk(); ... ?>
  • 18. • From operations within the class, class’s data / methods can be accessed / called by using: – $this = a variable that refers to the current instance of the class, and can be used only in the definition of the class. – The pointer operator -> (similar to Java’s object member access operator “.” ) – class Test { public $attribute; function f ($val) { $this -> attribute = $val; // $this is mandatory! } // if omitted, $attribute is treated } // as a local var in the function Using Data/Method Members 18
  • 19. • From outside the class, accessible (as determined by access modifiers) data and methods are accessed through a variable holding an instance of the class, by using the same pointer operator. class Test { public $attribute; } $t = new Test(); $t->attribute = “value”; echo $t->attribute; Using Data/Method Members 19
  • 20.  Visibility of a method or data member:  Public  Protected  Private By default, without the access specifies, class members are defined public. Defining and Using Variables, Constants and Functions 20
  • 21. • Class members declared public can be accessed everywhere. • Members declared protected can be accessed only within the class itself and by inherited classes • Members declared as private may only be accessed by the class that defines the member.
  • 22. Encapsulation • Data members are normally set inaccessible from outside the class (as well as certain types of methods) protecting them from the rest of the script and other classes. • This protection of class members is known as encapsulation.
  • 23. Encapsulation • <?php class App { private static $_user; public function User( ) { if( $this->_user == null ) { $this->_user = new User(); } return $this->_user; } } ?>
  • 24. Getter and setter functions
  • 25. Inheritance in PHP • Inheritance is a concept in object oriented programming. With the help of inheritance we can get all property and method of one class in another class. This is principle to take re- fusibility on upper level. Inheritance in php is introduced from php5 version.
  • 26. Inheritance • New classes can be defined very similar to existing ones. All we need to do is specify the differences between the new class and the existing one. • Data members and methods which are not defined as being private to a class are automatically accessible by the new class. • This is known as inheritance and is an extremely powerful and useful programming tool.
  • 27. Inheritance • class Animal { public $name; public function Greet() { return "Hello, I'm some sort of animal and my name is " . $this->name; } }
  • 28. Inheritance class Dog extends Animal { public function Greet() { return "Hello, I'm a dog and my name is " . $this->name; } }
  • 30. Overriding methods • Sometimes (when using inheritance,) you may need to change how a method works from the base class. • For example, let's say set_name() method in the 'employee' class, had to do something different than what it does in the 'person' class. • You 'override' the 'person' classes version of set_name(), by declaring the same method in 'employee'.
  • 32. OOP with PHP Overloading in PHP <?php class ShoppingCart{ function ShoppingCart(){ $to_call="ShoppingCart".func_num_args(); $args = func_get_args(); // return an array of arguments $args = implode(':',$args); $args = str_replace(“:”, “,”, $args); $run = “$this->$to_call ($args);”; // variable variable eval ($run); } function ShoppingCart1($x=”2”) { code1();} function ShoppingCart2($x=”2”,$y=”3”) { code2();} } ?>
  • 33. OOP with PHP Polymorphism • All class member functions are virtual by the definition class A { function draw() { echo "1"; } // not needed function boo() { $this->draw(); } } class B extends A { function draw() { echo "drawing B"; } } $b = new B(); $b->boo(); // outputs “drawing B”
  • 34. what is abstract class in php? • An abstract class is a class that contains at least one abstract method, which is a method without any actual code in it, just the name and the parameters, and that has been marked as "abstract". • The purpose of this is to provide a kind of template to inherit from and to force the inheriting class to implement the abstract methods. • An abstract class thus is something between a regular class and a pure interface. Also interfaces are a special case of abstract classes where ALL methods are abstract.
  • 36. PHP Interfaces • interfaces exist not as a base on which classes can extend but as a map of required functions. • The entire point of interfaces is to give you the flexibility to have your class be forced to implement multiple interfaces, but still not allow multiple inheritance. The issues with inheriting from multiple classes
  • 38. Differences between abstract class and interface in PHP • In abstract classes this is not necessary that every method should be abstract. But in interface every method is abstract. • Multiple and multilevel both type of inheritance is possible in interface. But single and multilevel inheritance is possible in abstract classes. • Method of php interface must be public only. Method in abstract class in php could be public or protected both. • In abstract class you can define as well as declare methods. But in interface you can only defined your methods.
  • 39. Object example: Fetch file from web 39 # create an HTTP request to fetch student.php $req = new HttpRequest("student.php", HttpRequest::METH_GET); $params = array("first_name" => $fname, "last_name" => $lname); $req->addPostFields($params); # send request and examine result $req->send(); $http_result_code = $req->getResponseCode(); # 200 means OK print "$http_result_coden"; print $req->getResponseBody(); PHP • PHP's HttpRequest object can fetch a document from the web CS380
  • 40. OOP with PHP Generic function for setting the member variables function Set ($varname, $value) { $this->$varname = $value; } $instance->Set ('size','5');
  • 41. OOP with PHP Serializing the objects • Partially overcomes the need for a persistent object • !!Saves only data members, not methods! (PHP4 is exception) <?php $myCart = new ShoppingCart(); $stream1 = serialize($myCart); // and store to file or db ... ... // retreive from file/db after a year.. $myLaterCart = unserialize($stream1); ?> • Not recommended to use!

Editor's Notes

  1. If ref var is assigned null -> destructor called if no other ref var left to that object!