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

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
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
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
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
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
 
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
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
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
 
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
 

Recently uploaded (20)

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 )
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
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
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
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...
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
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
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
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
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
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
 
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
 

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!