際際滷

際際滷Share a Scribd company logo
PHP Workshop #
PHP Classes
and
Object Orientation
PHP Workshop #
Reminder a function
 Reusable piece of code.
 Has its own local scope.
function my_func($arg1,$arg2) {
<< function statements >>
}
PHP Workshop #
Conceptually, what does a
function represent?
give the function something (arguments), it does
something with them, and then returns a result
Action or Method
PHP Workshop #
What is a class?
Conceptually, a class represents an
object, with associated methods
and variables
PHP Workshop #
Class Definition
<?php
class dog {
public $name;
public function bark() {
echo Woof!;
}
}
?>
An example class
definition for a dog.
The dog object has a
single attribute, the
name, and can
perform the action of
barking.
PHP Workshop #
Class Definition
<?php
class dog {
public $name;
public function bark() {
echo Woof!;
}
}
?>
class dog {
Define the name
of the class.
PHP Workshop #
Class Definition
<?php
class dog {
var $name
public function bark() {
echo Woof!;
}
}
?>
public $name;
Define an object
attribute (variable),
the dogs name.
PHP Workshop #
Class Definition
<?php
class dog {
public $name;
function bark() {
echo Woof!;
}
}
?>
public function bark() {
echo Woof!;
}
Define an
object action
(function), the
dogs bark.
PHP Workshop #
Class Definition
<?php
class dog {
public $name;
public function bark() {
echo Woof!;
}
}
?>
}
End the class
definition
PHP Workshop #
Class Defintion
Similar to defining a function..
The definition does not do anything by
itself. It is a blueprint, or description, of an
object. To do something, you need to use
the class
PHP Workshop #
Class Usage
<?php
require(dog.class.php);
$puppy = new dog();
$puppy->name = Rover;
echo {$puppy->name} says ;
$puppy->bark();
?>
PHP Workshop #
Class Usage
<?php
require(dog.class.php);
$puppy = new dog();
$puppy->name = Rover;
echo {$puppy->name} says ;
$puppy->bark();
?>
require(dog.class.php);
Include the class
definition
PHP Workshop #
Class Usage
<?php
require(dog.class.php);
$puppy = new dog();
$puppy->name = Rover;
echo {$puppy->name} says ;
$puppy->bark();
?>
$puppy = new dog();
Create a new
instance of the
class.
PHP Workshop #
Class Usage
<?php
require(dog.class.php);
$puppy = new dog();
$puppy->name = Rover;
echo {$puppy->name} says ;
$puppy->bark();
?>
$puppy->name = Rover;
Set the name
variable of this
instance to
Rover.
PHP Workshop #
Class Usage
<?php
require(dog.class.php);
$puppy = new dog();
$puppy->name = Rover;
echo {$puppy->name} says ;
$puppy->bark();
?>
echo {$puppy->name} says ;
Use the name
variable of this
instance in an
echo statement..
PHP Workshop #
Class Usage
<?php
require(dog.class.php);
$puppy = new dog();
$puppy->name = Rover;
echo {$puppy->name} says ;
$puppy->bark();
?>
$puppy->bark();
Use the dog
object bark
method.
PHP Workshop #
Class Usage
<?php
require(dog.class.php);
$puppy = new dog();
$puppy->name = Rover;
echo {$puppy->name} says ;
$puppy->bark();
?>
[example file: classes1.php]
PHP Workshop #
One dollar and one only
$puppy->name = Rover;
The most common mistake is to use more
than one dollar sign when accessing
variables. The following means something
entirely different..
$puppy->$name = Rover;
PHP Workshop #
Using attributes within the class..
 If you need to use the class variables
within any class actions, use the special
variable $this in the definition:
class dog {
public $name;
public function bark() {
echo $this->name. says Woof!;
}
}
PHP Workshop #
Constructor methods
 A constructor method is a function that is
automatically executed when the class is
first instantiated.
 Create a constructor by including a
function within the class definition with the
__construct name.
 Remember.. if the constructor requires
arguments, they must be passed when it is
instantiated!
PHP Workshop #
Constructor Example
<?php
class dog {
public $name;
public function __construct($nametext) {
$this->name = $nametext;
}
public function bark() {
echo Woof!;
}
}
?>
Constructor function
PHP Workshop #
Constructor Example
<?php

$puppy = new dog(Rover);

?> Constructor arguments
are passed during the
instantiation of the object.
PHP Workshop #
Class Scope
 Like functions, each instantiated object
has its own local scope.
e.g. if 2 different dog objects are
instantiated, $puppy1 and $puppy2, the
two dog names $puppy1->name and
$puppy2->name are entirely
independent..
PHP Workshop #
Inheritance
 The real power of using classes is the
property of inheritance  creating a
hierarchy of interlinked classes.
dog
poodle alsatian
parent
children
PHP Workshop #
Inheritance
 The child classes inherit all the methods
and variables of the parent class, and can
add extra ones of their own.
e.g. the child classes poodle inherits the
variable name and method bark from the
dog class, and can add extra ones
PHP Workshop #
Inheritance example
The American Kennel Club (AKC) recognizes three sizes of poodle - Standard,
Miniature, and Toy
class poodle extends dog {
public $type;
public function set_type($height) {
if ($height<10) {
$this->type = Toy;
} elseif ($height>15) {
$this->type = Standard;
} else {
$this->type = Miniature;
}
}
}
PHP Workshop #
Inheritance example
The American Kennel Club (AKC) recognizes three sizes of poodle - Standard,
Miniature, and Toy
class poodle extends dog {
public $type
public function set_type($height) {
if ($height<10) {
$this->type = Toy;
} elseif ($height>15) {
$this->type = Standard;
} else {
$this->type = Miniature;
}
}
}
class poodle extends dog {
Note the use of the
extends keyword to
indicate that the
poodle class is a child
of the dog class
PHP Workshop #
Inheritance example

$puppy = new poodle(Oscar);
$puppy->set_type(12); // 12 inches high!
echo Poodle is called {$puppy->name}, ;
echo of type {$puppy->type}, saying ;
echo $puppy->bark();
PHP Workshop #
a poodle will always Yip!
 It is possible to over-ride a parent method with a new
method if it is given the same name in the child class..
class poodle extends dog {

public function bark() {
echo Yip!;
}

}
PHP Workshop #
Child Constructors?
 If the child class possesses a constructor
function, it is executed and any parent
constructor is ignored.
 If the child class does not have a constructor, the
parents constructor is executed.
 If the child and parent does not have a
constructor, the grandparent constructor is
attempted
  etc.
PHP Workshop #
Objects within Objects
 It is perfectly possible to include objects within another
object..
class dogtag {
public $words;
}
class dog {
public $name;
public $tag;
public function bark() {
echo "Woof!n";
}
}

$puppy = new dog;
$puppy->name = Rover";
$poppy->tag = new dogtag;
$poppy->tag->words = blah;
PHP Workshop #
Deleting objects
 So far our objects have not been
destroyed till the end of our scripts..
 Like variables, it is possible to explicitly
destroy an object using the unset()
function.
PHP Workshop #
A copy, or not a copy..
 Entire objects can be passed as
arguments to functions, and can use all
methods/variables within the function.
 Remember however.. like functions the
object is COPIED when passed as an
argument unless you specify the argument
as a reference variable &$variable
PHP Workshop #
Why Object Orientate?
Reason 1
Once you have your head round the concept of
objects, intuitively named object orientated code
becomes easy to understand.
e.g.
$order->display_basket();
$user->card[2]->pay($order);
$order->display_status();
PHP Workshop #
Why Object Orientate?
Reason 2
Existing code becomes easier to maintain.
e.g. If you want to extend the capability of a
piece of code, you can merely edit the
class definitions
PHP Workshop #
Why Object Orientate?
Reason 3
New code becomes much quicker to write
once you have a suitable class library.
e.g. Need a new object..? Usually can
extend an existing object. A lot of high
quality code is distributed as classes (e.g.
http://pear.php.net).
PHP Workshop #
There is a lot more
 We have really only touched the edge of
object orientated programming
http://www.php.net/manual/en/language.oop.php
  but I dont want to confuse you too
much!
PHP Workshop #
PHP4 vs. PHP5
 OOP purists will tell you that the object
support in PHP4 is sketchy. They are right,
in that a lot of features are missing.
 PHP5 OOP system has had a big redesign
and is much better.
but it is worth it to produce OOP
code in either PHP4 or PHP5
PHP Workshop #
PHP Data Object (PDO)
PHP Workshop #
What is PDO?
 PDO is a PHP extension to formalise
PHP's database connections by creating a
uniform interface. This allows developers
to create code which is portable across
many databases and platforms.
 PDO is not just another abstraction layer
like PEAR DB or ADOdb.
PHP Workshop #
Why use PDO?
 Portability
 Performance
 Power
 Easy
 Runtime Extensible
PHP Workshop #
What databases does it support?
 Microsoft SQL Server / Sybase
 Firebird / Interbase
 DB2 / INFORMIX (IBM)
 MySQL
 OCI (Oracle Call Interface)
 ODBC
 PostgreSQL
 SQLite
PHP Workshop #
DSNs
 In general
drivername:<driver-specific-stuff>
 mysql:host=name;dbname=dbname
 odbc:odbc_dsn
 oci:dbname=dbname;charset=charset
 sqlite:/path/to/db/file
 sqlite::memory:
PHP Workshop #
Connect to MySQL
PHP Workshop #
Connect to SQLite (file)
PHP Workshop #
Connect to SQLite (memory)
PHP Workshop #
Connect to Oracle
PHP Workshop #
Connect to ODBC
PHP Workshop #
Close a Database Connection
PHP Workshop #
Persistent PDO Connection
 Connection stays alive between
requests
$dbh = new PDO($dsn, $user, $pass,
array(
PDO_ATTR_PERSISTENT => true
)
);
PHP Workshop #
PDO Query (INSERT)
PHP Workshop #
PDO Query (UPDATE)
PHP Workshop #
PDO Query (SELECT)
PHP Workshop #
Error Handling (1)
PHP Workshop #
Error Handling (2)
PHP Workshop #
Error Handling (3)
PHP Workshop #
Error Handling (4)
PHP Workshop #
Prepared statements
PHP Workshop #
Transactions
PHP Workshop #
Get Last Insert Id
PHP Workshop #
Benchmark
MySQL SELECT Benchmark Results, 1000 Requests
Library Concurrency Total Time Requests/Sec. Speedup
ADOdb 1 20.90/sec 47.84 -
PDO 1 0.73/sec 1358.62 +2840%
ADOdb 50 10.78/sec 99.23 -
PDO 50 0.54/sec 1850.90 +1865%
ADOdb 100 10.44/sec 95.78 -
PDO 100 0.53/sec 1869.33 +1952%
PHP Workshop #
Questions

Recommended

SQL Devlopment for 10 ppt
SQL Devlopment for 10 ppt
Tanay Kishore Mishra
Oops implemetation material
Oops implemetation material
Deepak Solanki
PHP Classes and OOPS Concept
PHP Classes and OOPS Concept
Dot Com Infoway - Custom Software, Mobile, Web Application Development and Digital Marketing Company
10 classes
10 classes
Naomi Boyoro
Class and Objects in PHP
Class and Objects in PHP
Ramasubbu .P
OOP is more than Cars and Dogs
OOP is more than Cars and Dogs
Chris Tankersley
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
ShaownRoy1
PHP-05-Objects.ppt
PHP-05-Objects.ppt
rani marri
UNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
UNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
Synapseindia object oriented programming in php
Synapseindia object oriented programming in php
Synapseindiappsdevelopment
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017
Alena Holligan
UNIT-IV WT web technology for 1st year cs
UNIT-IV WT web technology for 1st year cs
javed75
OOP Is More Than Cars and Dogs
OOP Is More Than Cars and Dogs
Chris Tankersley
OOP Is More Than Cars and Dogs
OOP Is More Than Cars and Dogs
Chris Tankersley
Object oreinted php | OOPs
Object oreinted php | OOPs
Ravi Bhadauria
Oops concept in php
Oops concept in php
selvabalaji k
Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018
Mark Niebergall
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
ajayparmeshwarmahaja
Introduction to PHP and MySql basics.pptx
Introduction to PHP and MySql basics.pptx
PriyankaKupneshi
Object oriented programming in php 5
Object oriented programming in php 5
Sayed Ahmed
Object oriented programming in php 5
Object oriented programming in php 5
Sayed Ahmed
Object Oriented PHP5
Object Oriented PHP5
Jason Austin
PHP OOP
PHP OOP
Oscar Merida
OOP Day 2
OOP Day 2
Brian Fenton
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18
Alena Holligan
Introduction to php oop
Introduction to php oop
baabtra.com - No. 1 supplier of quality freshers
Introduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdf
TechSoup
Community Health Nursing Approaches, Concepts, Roles & Responsibilities Uni...
Community Health Nursing Approaches, Concepts, Roles & Responsibilities Uni...
RAKESH SAJJAN

More Related Content

Similar to 06-classes.ppt (copy).pptx (20)

UNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
UNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
Synapseindia object oriented programming in php
Synapseindia object oriented programming in php
Synapseindiappsdevelopment
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017
Alena Holligan
UNIT-IV WT web technology for 1st year cs
UNIT-IV WT web technology for 1st year cs
javed75
OOP Is More Than Cars and Dogs
OOP Is More Than Cars and Dogs
Chris Tankersley
OOP Is More Than Cars and Dogs
OOP Is More Than Cars and Dogs
Chris Tankersley
Object oreinted php | OOPs
Object oreinted php | OOPs
Ravi Bhadauria
Oops concept in php
Oops concept in php
selvabalaji k
Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018
Mark Niebergall
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
ajayparmeshwarmahaja
Introduction to PHP and MySql basics.pptx
Introduction to PHP and MySql basics.pptx
PriyankaKupneshi
Object oriented programming in php 5
Object oriented programming in php 5
Sayed Ahmed
Object oriented programming in php 5
Object oriented programming in php 5
Sayed Ahmed
Object Oriented PHP5
Object Oriented PHP5
Jason Austin
PHP OOP
PHP OOP
Oscar Merida
OOP Day 2
OOP Day 2
Brian Fenton
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18
Alena Holligan
Introduction to php oop
Introduction to php oop
baabtra.com - No. 1 supplier of quality freshers
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
Synapseindia object oriented programming in php
Synapseindia object oriented programming in php
Synapseindiappsdevelopment
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017
Alena Holligan
UNIT-IV WT web technology for 1st year cs
UNIT-IV WT web technology for 1st year cs
javed75
OOP Is More Than Cars and Dogs
OOP Is More Than Cars and Dogs
Chris Tankersley
OOP Is More Than Cars and Dogs
OOP Is More Than Cars and Dogs
Chris Tankersley
Object oreinted php | OOPs
Object oreinted php | OOPs
Ravi Bhadauria
Oops concept in php
Oops concept in php
selvabalaji k
Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018
Mark Niebergall
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
ajayparmeshwarmahaja
Introduction to PHP and MySql basics.pptx
Introduction to PHP and MySql basics.pptx
PriyankaKupneshi
Object oriented programming in php 5
Object oriented programming in php 5
Sayed Ahmed
Object oriented programming in php 5
Object oriented programming in php 5
Sayed Ahmed
Object Oriented PHP5
Object Oriented PHP5
Jason Austin
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18
Alena Holligan

Recently uploaded (20)

Introduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdf
TechSoup
Community Health Nursing Approaches, Concepts, Roles & Responsibilities Uni...
Community Health Nursing Approaches, Concepts, Roles & Responsibilities Uni...
RAKESH SAJJAN
LDM Recording Presents Yogi Goddess by LDMMIA
LDM Recording Presents Yogi Goddess by LDMMIA
LDM & Mia eStudios
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
Belicia R.S
Environmental Science, Environmental Health, and Sanitation Unit 3 | B.Sc N...
Environmental Science, Environmental Health, and Sanitation Unit 3 | B.Sc N...
RAKESH SAJJAN
LDMMIA Practitioner Level Orientation Updates
LDMMIA Practitioner Level Orientation Updates
LDM & Mia eStudios
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
Birnagar High School Platinum Jubilee Quiz.pptx
Birnagar High School Platinum Jubilee Quiz.pptx
Sourav Kr Podder
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
K12 Tableau User Group virtual event June 18, 2025
K12 Tableau User Group virtual event June 18, 2025
dogden2
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
Celine George
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
This is why students from these 44 institutions have not received National Se...
This is why students from these 44 institutions have not received National Se...
Kweku Zurek
The Man In The Back Exceptional Delaware.pdf
The Man In The Back Exceptional Delaware.pdf
dennisongomezk
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
How to Manage Different Customer Addresses in Odoo 18 Accounting
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George
Introduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdf
TechSoup
Community Health Nursing Approaches, Concepts, Roles & Responsibilities Uni...
Community Health Nursing Approaches, Concepts, Roles & Responsibilities Uni...
RAKESH SAJJAN
LDM Recording Presents Yogi Goddess by LDMMIA
LDM Recording Presents Yogi Goddess by LDMMIA
LDM & Mia eStudios
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
Belicia R.S
Environmental Science, Environmental Health, and Sanitation Unit 3 | B.Sc N...
Environmental Science, Environmental Health, and Sanitation Unit 3 | B.Sc N...
RAKESH SAJJAN
LDMMIA Practitioner Level Orientation Updates
LDMMIA Practitioner Level Orientation Updates
LDM & Mia eStudios
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
Birnagar High School Platinum Jubilee Quiz.pptx
Birnagar High School Platinum Jubilee Quiz.pptx
Sourav Kr Podder
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
K12 Tableau User Group virtual event June 18, 2025
K12 Tableau User Group virtual event June 18, 2025
dogden2
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
Celine George
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
This is why students from these 44 institutions have not received National Se...
This is why students from these 44 institutions have not received National Se...
Kweku Zurek
The Man In The Back Exceptional Delaware.pdf
The Man In The Back Exceptional Delaware.pdf
dennisongomezk
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
How to Manage Different Customer Addresses in Odoo 18 Accounting
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George

06-classes.ppt (copy).pptx

  • 1. PHP Workshop # PHP Classes and Object Orientation
  • 2. PHP Workshop # Reminder a function Reusable piece of code. Has its own local scope. function my_func($arg1,$arg2) { << function statements >> }
  • 3. PHP Workshop # Conceptually, what does a function represent? give the function something (arguments), it does something with them, and then returns a result Action or Method
  • 4. PHP Workshop # What is a class? Conceptually, a class represents an object, with associated methods and variables
  • 5. PHP Workshop # Class Definition <?php class dog { public $name; public function bark() { echo Woof!; } } ?> An example class definition for a dog. The dog object has a single attribute, the name, and can perform the action of barking.
  • 6. PHP Workshop # Class Definition <?php class dog { public $name; public function bark() { echo Woof!; } } ?> class dog { Define the name of the class.
  • 7. PHP Workshop # Class Definition <?php class dog { var $name public function bark() { echo Woof!; } } ?> public $name; Define an object attribute (variable), the dogs name.
  • 8. PHP Workshop # Class Definition <?php class dog { public $name; function bark() { echo Woof!; } } ?> public function bark() { echo Woof!; } Define an object action (function), the dogs bark.
  • 9. PHP Workshop # Class Definition <?php class dog { public $name; public function bark() { echo Woof!; } } ?> } End the class definition
  • 10. PHP Workshop # Class Defintion Similar to defining a function.. The definition does not do anything by itself. It is a blueprint, or description, of an object. To do something, you need to use the class
  • 11. PHP Workshop # Class Usage <?php require(dog.class.php); $puppy = new dog(); $puppy->name = Rover; echo {$puppy->name} says ; $puppy->bark(); ?>
  • 12. PHP Workshop # Class Usage <?php require(dog.class.php); $puppy = new dog(); $puppy->name = Rover; echo {$puppy->name} says ; $puppy->bark(); ?> require(dog.class.php); Include the class definition
  • 13. PHP Workshop # Class Usage <?php require(dog.class.php); $puppy = new dog(); $puppy->name = Rover; echo {$puppy->name} says ; $puppy->bark(); ?> $puppy = new dog(); Create a new instance of the class.
  • 14. PHP Workshop # Class Usage <?php require(dog.class.php); $puppy = new dog(); $puppy->name = Rover; echo {$puppy->name} says ; $puppy->bark(); ?> $puppy->name = Rover; Set the name variable of this instance to Rover.
  • 15. PHP Workshop # Class Usage <?php require(dog.class.php); $puppy = new dog(); $puppy->name = Rover; echo {$puppy->name} says ; $puppy->bark(); ?> echo {$puppy->name} says ; Use the name variable of this instance in an echo statement..
  • 16. PHP Workshop # Class Usage <?php require(dog.class.php); $puppy = new dog(); $puppy->name = Rover; echo {$puppy->name} says ; $puppy->bark(); ?> $puppy->bark(); Use the dog object bark method.
  • 17. PHP Workshop # Class Usage <?php require(dog.class.php); $puppy = new dog(); $puppy->name = Rover; echo {$puppy->name} says ; $puppy->bark(); ?> [example file: classes1.php]
  • 18. PHP Workshop # One dollar and one only $puppy->name = Rover; The most common mistake is to use more than one dollar sign when accessing variables. The following means something entirely different.. $puppy->$name = Rover;
  • 19. PHP Workshop # Using attributes within the class.. If you need to use the class variables within any class actions, use the special variable $this in the definition: class dog { public $name; public function bark() { echo $this->name. says Woof!; } }
  • 20. PHP Workshop # Constructor methods A constructor method is a function that is automatically executed when the class is first instantiated. Create a constructor by including a function within the class definition with the __construct name. Remember.. if the constructor requires arguments, they must be passed when it is instantiated!
  • 21. PHP Workshop # Constructor Example <?php class dog { public $name; public function __construct($nametext) { $this->name = $nametext; } public function bark() { echo Woof!; } } ?> Constructor function
  • 22. PHP Workshop # Constructor Example <?php $puppy = new dog(Rover); ?> Constructor arguments are passed during the instantiation of the object.
  • 23. PHP Workshop # Class Scope Like functions, each instantiated object has its own local scope. e.g. if 2 different dog objects are instantiated, $puppy1 and $puppy2, the two dog names $puppy1->name and $puppy2->name are entirely independent..
  • 24. PHP Workshop # Inheritance The real power of using classes is the property of inheritance creating a hierarchy of interlinked classes. dog poodle alsatian parent children
  • 25. PHP Workshop # Inheritance The child classes inherit all the methods and variables of the parent class, and can add extra ones of their own. e.g. the child classes poodle inherits the variable name and method bark from the dog class, and can add extra ones
  • 26. PHP Workshop # Inheritance example The American Kennel Club (AKC) recognizes three sizes of poodle - Standard, Miniature, and Toy class poodle extends dog { public $type; public function set_type($height) { if ($height<10) { $this->type = Toy; } elseif ($height>15) { $this->type = Standard; } else { $this->type = Miniature; } } }
  • 27. PHP Workshop # Inheritance example The American Kennel Club (AKC) recognizes three sizes of poodle - Standard, Miniature, and Toy class poodle extends dog { public $type public function set_type($height) { if ($height<10) { $this->type = Toy; } elseif ($height>15) { $this->type = Standard; } else { $this->type = Miniature; } } } class poodle extends dog { Note the use of the extends keyword to indicate that the poodle class is a child of the dog class
  • 28. PHP Workshop # Inheritance example $puppy = new poodle(Oscar); $puppy->set_type(12); // 12 inches high! echo Poodle is called {$puppy->name}, ; echo of type {$puppy->type}, saying ; echo $puppy->bark();
  • 29. PHP Workshop # a poodle will always Yip! It is possible to over-ride a parent method with a new method if it is given the same name in the child class.. class poodle extends dog { public function bark() { echo Yip!; } }
  • 30. PHP Workshop # Child Constructors? If the child class possesses a constructor function, it is executed and any parent constructor is ignored. If the child class does not have a constructor, the parents constructor is executed. If the child and parent does not have a constructor, the grandparent constructor is attempted etc.
  • 31. PHP Workshop # Objects within Objects It is perfectly possible to include objects within another object.. class dogtag { public $words; } class dog { public $name; public $tag; public function bark() { echo "Woof!n"; } } $puppy = new dog; $puppy->name = Rover"; $poppy->tag = new dogtag; $poppy->tag->words = blah;
  • 32. PHP Workshop # Deleting objects So far our objects have not been destroyed till the end of our scripts.. Like variables, it is possible to explicitly destroy an object using the unset() function.
  • 33. PHP Workshop # A copy, or not a copy.. Entire objects can be passed as arguments to functions, and can use all methods/variables within the function. Remember however.. like functions the object is COPIED when passed as an argument unless you specify the argument as a reference variable &$variable
  • 34. PHP Workshop # Why Object Orientate? Reason 1 Once you have your head round the concept of objects, intuitively named object orientated code becomes easy to understand. e.g. $order->display_basket(); $user->card[2]->pay($order); $order->display_status();
  • 35. PHP Workshop # Why Object Orientate? Reason 2 Existing code becomes easier to maintain. e.g. If you want to extend the capability of a piece of code, you can merely edit the class definitions
  • 36. PHP Workshop # Why Object Orientate? Reason 3 New code becomes much quicker to write once you have a suitable class library. e.g. Need a new object..? Usually can extend an existing object. A lot of high quality code is distributed as classes (e.g. http://pear.php.net).
  • 37. PHP Workshop # There is a lot more We have really only touched the edge of object orientated programming http://www.php.net/manual/en/language.oop.php but I dont want to confuse you too much!
  • 38. PHP Workshop # PHP4 vs. PHP5 OOP purists will tell you that the object support in PHP4 is sketchy. They are right, in that a lot of features are missing. PHP5 OOP system has had a big redesign and is much better. but it is worth it to produce OOP code in either PHP4 or PHP5
  • 39. PHP Workshop # PHP Data Object (PDO)
  • 40. PHP Workshop # What is PDO? PDO is a PHP extension to formalise PHP's database connections by creating a uniform interface. This allows developers to create code which is portable across many databases and platforms. PDO is not just another abstraction layer like PEAR DB or ADOdb.
  • 41. PHP Workshop # Why use PDO? Portability Performance Power Easy Runtime Extensible
  • 42. PHP Workshop # What databases does it support? Microsoft SQL Server / Sybase Firebird / Interbase DB2 / INFORMIX (IBM) MySQL OCI (Oracle Call Interface) ODBC PostgreSQL SQLite
  • 43. PHP Workshop # DSNs In general drivername:<driver-specific-stuff> mysql:host=name;dbname=dbname odbc:odbc_dsn oci:dbname=dbname;charset=charset sqlite:/path/to/db/file sqlite::memory:
  • 45. PHP Workshop # Connect to SQLite (file)
  • 46. PHP Workshop # Connect to SQLite (memory)
  • 49. PHP Workshop # Close a Database Connection
  • 50. PHP Workshop # Persistent PDO Connection Connection stays alive between requests $dbh = new PDO($dsn, $user, $pass, array( PDO_ATTR_PERSISTENT => true ) );
  • 51. PHP Workshop # PDO Query (INSERT)
  • 52. PHP Workshop # PDO Query (UPDATE)
  • 53. PHP Workshop # PDO Query (SELECT)
  • 54. PHP Workshop # Error Handling (1)
  • 55. PHP Workshop # Error Handling (2)
  • 56. PHP Workshop # Error Handling (3)
  • 57. PHP Workshop # Error Handling (4)
  • 60. PHP Workshop # Get Last Insert Id
  • 61. PHP Workshop # Benchmark MySQL SELECT Benchmark Results, 1000 Requests Library Concurrency Total Time Requests/Sec. Speedup ADOdb 1 20.90/sec 47.84 - PDO 1 0.73/sec 1358.62 +2840% ADOdb 50 10.78/sec 99.23 - PDO 50 0.54/sec 1850.90 +1865% ADOdb 100 10.44/sec 95.78 - PDO 100 0.53/sec 1869.33 +1952%