SlideShare ist ein Scribd-Unternehmen logo
1 von 52
Chapter 10
Developing
Object-Oriented PHP
PHP Programming with MySQL
2nd
Edition
2PHP Programming with MySQL, 2nd Edition
Objectives
In this chapter, you will:
• Study object-oriented programming concepts
• Use objects in PHP scripts
• Declare data members in classes
• Work with class member functions
3PHP Programming with MySQL, 2nd Edition
Introduction to Object-Oriented
Programming
• Object-oriented programming (OOP) refers
the concept of merging related variables and
functions into a single interface
• An object refers to programming code and data
that can be treated as an individual unit or
component
• Objects are often also called components
4PHP Programming with MySQL, 2nd Edition
Introduction to Object-Oriented
Programming (continued)
• Data refers to information contained within
variables or other types of storage structures
• The functions associated with an object are
called methods
• The variables that are associated with an object
are called properties or attributes
• Popular object-oriented programming languages
include C++, Java, and Visual Basic
5PHP Programming with MySQL, 2nd Edition
Introduction to Object-Oriented
Programming (continued)
Figure 10-1 Accounting program
6PHP Programming with MySQL, 2nd Edition
Understanding Encapsulation
• Objects are encapsulated – all code and
required data are contained within the object
itself
• Encapsulated objects hide all internal code
and data
• An interface refers to the methods and
properties that are required for a source
program to communicate with an object
7PHP Programming with MySQL, 2nd Edition
Understanding Encapsulation
(continued)
• Encapsulated objects allow users to see only the
methods and properties of the object that you
allow them to see
• Encapsulation reduces the complexity of the
code
• Encapsulation prevents other programmers from
accidentally introducing a bug into a program, or
stealing code
8PHP Programming with MySQL, 2nd Edition
Object-Oriented Programming
and Classes
• The code, methods, attributes, and other
information that make up an object are
organized into classes
• An instance is an object that has been created
from an existing class
• Creating an object from an existing class is
called instantiating the object
• An object inherits its methods and properties
from a class — it takes on the characteristics of
the class on which it is based
9PHP Programming with MySQL, 2nd Edition
Using Objects in PHP Scripts
• Declare an object in PHP by using the new
operator with a class constructor
• A class constructor is a special function with
the same name as its class that is called
automatically when an object from the class is
instantiated
• The syntax for instantiating an object is:
$ObjectName = new ClassName();
10PHP Programming with MySQL, 2nd Edition
Using Objects in PHP Scripts
(continued)
• After an object is instantiated, use a hyphen and
a greater-than symbol (->) to access the
methods and properties contained in the object
• Together, these two characters are referred to
as member selection notation
• With member selection notation, one or more
characters are appended to an object, followed
by the name of a method or property
11PHP Programming with MySQL, 2nd Edition
Using Objects in PHP Scripts
(continued)
• With methods, include a set of parentheses at
the end of the method name, just as with
functions
• Like functions, methods can also accept
arguments
$Checking->getBalance();
$CheckNumber = 1022;
$Checking->getCheckAmount($CheckNumber);
12PHP Programming with MySQL, 2nd Edition
Working with Database
Connections as Objects
• Access MySQL database connections as objects
by instantiating an object from the mysqli class
• To connect to a MySQL database server using
procedural syntax:
$DBConnect = mysql_connect("php_db", "dongosselin",
"rosebud");
mysql_select_db("real_estate", $DBConnect);
• To connect to the MySQL database server using
object-oriented style:
$DBConnect = new mysqli("php_db", "dongosselin",
"rosebud", "real_estate");
13PHP Programming with MySQL, 2nd Edition
Handling MySQL Errors
• This statement uses the mysqli() constructor
function to instantiate a mysqli class object
named $DBConnect
$DBConnect = @new mysqli("php_db", "dgosselin",
"rosebud");
• To explicitly close the database connection, use
the close() method of the mysqli class
$DBConnect->close();
14PHP Programming with MySQL, 2nd Edition
Handling MySQL Errors (continued)
• With object-oriented style, check whether a
value is assigned to the
mysqli_connect_errno() or
mysqli_connect_error() functions
$DBConnect = @new mysqli("php.db", "dgosselin",
"rosebud");
if ($DBConnect->connect_errno){
echo("<p>Unable to connect to the database
server.</p>"
. "<p>Error code " . $DBConnect->connect_errno
. ": " . $DBConnect->connect_error. "</p>n";
else {
//code to execute if the connection fails
}
15PHP Programming with MySQL, 2nd Edition
Executing SQL Statements
• With object-oriented style, use the query()
method of the mysqli class
• To return the fields in the current row of a
resultset into an indexed array use:
– The fetch_row() method of the mysqli
class
• To return the fields in the current row of a
resultset into an associative array use:
– The fetch_assoc() method of the msqli
class
16PHP Programming with MySQL, 2nd Edition
Executing SQL Statements
(continued)
$TableName = "company_cars";
$SQLstring = "SELECT * FROM $TableName";
$QueryResult = @$DBConnect->query($SQLstring);
if ($QueryResult === FALSE)
echo "<p>Unable to execute the query. " .
"Error code " . $DBConnect->errno .
": " . $DBConnect->error . "</p>n";
else {
echo "<table width='100%' border='1'>n";
echo
"<tr><th>License</th><th>Make</th><th>Model</th>" .
"<th>Mileage</th><th>Year</th></tr>n";
17PHP Programming with MySQL, 2nd Edition
Executing SQL Statements
(continued)
…
while (($Row = $QueryResult->fetch_row()) !== FALSE) {
echo "<tr><td>{$Row[0]}</td>";
echo "<td>{$Row[1]}</td>";
echo "<td>{$Row[2]}</td>";
echo "<td align='right'>{$Row[3]}</td>";
echo "<td>{$Row[4]}</td></tr>n";
}
echo "</table>n";
}
18PHP Programming with MySQL, 2nd Edition
Defining Custom PHP Classes
• Data structure refers to a system for organizing
data
• The functions and variables defined in a class
are called class members
• Class variables are referred to as data
members or member variables
• Class functions are referred to as member
functions or function members
19PHP Programming with MySQL, 2nd Edition
Defining Custom PHP Classes
(continued)
• Classes:
– Help make complex programs easier to manage
– Hide information that users of a class do not need
to access or know about
– Make it easier to reuse code or distribute your
code to others for use in their programs
• Inherited characteristics allow you to build new
classes based on existing classes without
having to rewrite the code contained in the
existing one
20PHP Programming with MySQL, 2nd Edition
Creating a Class Definition
• To create a class in PHP, use the class
keyword to write a class definition
• A class definition contains the data members
and member functions that make up the class
• The syntax for defining a class is:
class ClassName {
data member and member function definitions
}
21PHP Programming with MySQL, 2nd Edition
Creating a Class Definition
(continued)
• The ClassName portion of the class definition is
the name of the new class
• Class names usually begin with an uppercase
letter to distinguish them from other identifiers
• Within the class’s curly braces, declare the data
type and field names for each piece of
information stored in the structure
class BankAccount {
data member and member function definitions
}
$Checking = new BankAccount();
22PHP Programming with MySQL, 2nd Edition
Creating a Class Definition
(continued)
• Class names in a class definition are not
followed by parentheses, as are function
names in a function definition
$Checking = new BankAccount();
echo 'The $Checking object is instantiated from the '
. get_class($Checking) . " class.</p>";
• Use the instanceof operator to determine
whether an object is instantiated from a given
class
• Use the class_exists() to determine if a
class exists
23PHP Programming with MySQL, 2nd Edition
Storing Classes in External Files
• PHP provides the following functions that allow
you to use external files in your PHP scripts:
– include()
– require()
– include_once()
– require_once()
• You pass to each function the name and path of
the external file you want to use
24PHP Programming with MySQL, 2nd Edition
Storing Classes in External Files
(continued)
• include() and require() functions both
insert the contents of an external file, called an
include file, into a PHP script
• include_once() and require_once()
functions only include an external file once
during the processing of a script
• Any PHP code must be contained within a PHP
script section (<?php ... ?>) in an external
file
25PHP Programming with MySQL, 2nd Edition
Collecting Garbage
• Garbage collection refers to cleaning up or
reclaiming memory that is reserved by a
program
• PHP knows when your program no longer needs
a variable or object and automatically cleans up
the memory for you
• The one exception is with open database
connections
26PHP Programming with MySQL, 2nd Edition
Information Hiding
• Information hiding states that any class
members that other programmers, sometimes
called clients, do not need to access or know
about should be hidden
• Helps minimize the amount of information that
needs to pass in and out of an object
• Reduces the complexity of the code that clients
see
• Prevents other programmers from accidentally
introducing a bug into a program by modifying a
class’s internal workings
27PHP Programming with MySQL, 2nd Edition
Using Access Specifiers
• Access specifiers control a client’s access to
individual data members and member functions
• There are three levels of access specifiers in
PHP: public, private, and protected
• The public access specifier allows anyone to
call a class’s member function or to modify and
retrieve a data member
28PHP Programming with MySQL, 2nd Edition
Using Access Specifiers
(continued)
• The private access specifier prevents clients
from calling member functions or accessing data
members and is one of the key elements in
information hiding
• Private access does not restrict a class’s internal
access to its own members
• Private access restricts clients from accessing
class members
29PHP Programming with MySQL, 2nd Edition
Using Access Specifiers
(continued)
• Include an access specifier at the beginning of a
data member declaration statement
class BankAccount {
public $Balance = 0;
}
• Always assign an initial value to a data member
when you first declare it
class BankAccount {
public $Balance = 1 + 2;
}
30PHP Programming with MySQL, 2nd Edition
Serializing Objects
• Serialization refers to the process of converting
an object into a string that you can store for
reuse
• Serialization stores both data members and
member functions into strings
• To serialize an object, pass an object name to
the serialize() function
$SavedAccount = serialize($Checking);
31PHP Programming with MySQL, 2nd Edition
Serializing Objects (continued)
• To convert serialized data back into an object,
you use the unserialize() function
$Checking = unserialize($SavedAccount);
• Serialization is also used to store the data in
large arrays
• To use serialized objects between scripts,
assign a serialized object to a session variable
session_start();
$_SESSION('SavedAccount') = serialize($Checking);
32PHP Programming with MySQL, 2nd Edition
Working with Member Functions
• Create public member functions for any
functions that clients need to access
• Create private member functions for any
functions that clients do not need to access
• Access specifiers control a client’s access to
individual data members and member functions
33PHP Programming with MySQL, 2nd Edition
Working with Member Functions
(continued)
class BankAccount {
public $Balance = 958.20;
public function withdrawal($Amount) {
$this->Balance -= $Amount;
}
}
if (class_exists("BankAccount"))
$Checking = new BankAccount();
else
exit("<p>The BankAccount class is not available!</p>");
printf("<p>Your checking account balance is $%.2f.</p>",
$Checking->Balance);
$Cash = 200;
$Checking->withdrawal(200);
printf("<p>After withdrawing $%.2f, your checking account balance
is $%.2f.</p>", $Cash, $Checking->Balance);
34PHP Programming with MySQL, 2nd Edition
Using the $this Reference
• Outside of a class, refer to the members of the
object using the name of the object, the member
selection nation (-), and the name of the function
or variable
• Within a class function definition, use $this to
refer to the current object of the class
$this->AccountNumber = 0;
35PHP Programming with MySQL, 2nd Edition
Initializing with Constructor
Functions
• A constructor function is a special function
that is called automatically when an object from
a class is instantiated
class BankAccount {
private $AccountNumber;
private $CustomerName;
private $Balance;
function __construct() {
$this->AccountNumber = 0;
$this->Balance = 0;
$this->CustomerName = "";
}
}
36PHP Programming with MySQL, 2nd Edition
Initializing with Constructor
Functions (continued)
• The __construct() function takes
precedence over a function with the same name
as the class
• Constructor functions are commonly used in
PHP to handle database connection tasks
37PHP Programming with MySQL, 2nd Edition
Cleaning Up with Destructor
Functions
• A default constructor function is called when a
class object is first instantiated
• A destructor function is called when the object
is destroyed
• A destructor function cleans up any resources
allocated to an object after the object is
destroyed
38PHP Programming with MySQL, 2nd Edition
Cleaning Up with Destructor
Functions (continued)
• A destructor function is commonly called in two
ways:
– When a script ends
– When you manually delete an object with
the unset() function
• To add a destructor function to a PHP class,
create a function named __destruct()
39PHP Programming with MySQL, 2nd Edition
Cleaning Up with Destructor
Functions (continued)
function __construct() {
$DBConnect = new mysqli("php_db",
"dongosselin","rosebud",
"real_estate");
}
function __destruct() {
$DBConnect->close();
}
40PHP Programming with MySQL, 2nd Edition
Writing Accessor Functions
• Accessor functions are public member
functions that a client can call to retrieve or
modify the value of a data member
• Accessor functions often begin with the words
“set” or “get”
• Set functions modify data member values
• Get functions retrieve data member values
41PHP Programming with MySQL, 2nd Edition
Writing Accessor Functions
(continued)
class BankAccount {
private $Balance = 0;
public function setBalance($NewValue) {
$this->Balance = $NewValue;
}
public function getBalance() {
return $this->Balance;
}
}
if (class_exists("BankAccount"))
$Checking = new BankAccount();
else
exit("<p>The BankAccount class is not available!</p>");
$Checking->setBalance(100);
echo "<p>Your checking account balance is "
. $Checking->getBalance() . "</p>n";
42PHP Programming with MySQL, 2nd Edition
Serialization Functions
• When you serialize an object with the
serialize() function, PHP looks in the
object’s class for a special function named
__sleep()
• The primary reason for including a __sleep()
function in a class is to specify which data
members of the class to serialize
43PHP Programming with MySQL, 2nd Edition
Serialization Functions (continued)
• If you do not include a __sleep() function in
your class, the serialize() function serializes
all of its data members
function __sleep() {
$SerialVars = array('Balance');
return $SerialVars;
}
• When the unserialize() function executes,
PHP looks in the object’s class for a special
function named __wakeup()
44PHP Programming with MySQL, 2nd Edition
Summary
• The term “object-oriented programming
(OOP)” refers to the creation of reusable
software objects that can be easily incorporated
into multiple programs. The term “object”
specifically refers to programming code and data
that can be treated as an individual unit or
component (object)
• The term “data” refers to information contained
within variables or other types of storage
structures
45PHP Programming with MySQL, 2nd Edition
Summary (continued)
• The functions associated with an object are
called methods, and the variables associated
with an object are called properties or
attributes
• Objects are encapsulated, which means that all
code and required data are contained within the
object itself
• An interface represents elements required for a
source program to communicate with an object
46PHP Programming with MySQL, 2nd Edition
Summary (continued)
• In object-oriented programming, the code,
methods, attributes, and other information that
make up an object are organized into classes
• An instance is an object that has been created
from an existing class. When you create an
object from an existing class, you are
“instantiating the object”
47PHP Programming with MySQL, 2nd Edition
Summary (continued)
• A particular instance of an object inherits its
methods and properties from a class—that is, it
takes on the characteristics of the class on
which it is based
• A constructor is a special function with the
same name as its class; it is called automatically
when an object from the class is instantiated
• The term “data structure” refers to a system for
organizing data
48PHP Programming with MySQL, 2nd Edition
Summary (continued)
• The functions and variables defined in a class
are called class members. Class variables are
referred to as data members or member
variables, whereas class functions are referred
to as member functions or function members
• A class definition contains the data members
and member functions that make up the class
49PHP Programming with MySQL, 2nd Edition
Summary (continued)
• PHP provides the following functions that allow
you to use external files in your PHP scripts:
include(), require(), include_once(),
and require_once()
• The principle of information hiding states that
class members should be hidden when other
programmers do not need to access or know
about them
• Access specifiers control a client’s access to
individual data members and member functions
50PHP Programming with MySQL, 2nd Edition
Summary (continued)
• Serialization refers to the process of converting
an object into a string that you can store for
reuse
• A constructor function is a special function
that is called automatically when an object from
a class is instantiated
• A destructor function cleans up any resources
allocated to an object after the object is
destroyed
51PHP Programming with MySQL, 2nd Edition
Summary (continued)
• Accessor functions are public member
functions that a client can call to retrieve the
value of a data member
• Mutator functions are public member functions
that a client can call to modify the value of a
data member
52PHP Programming with MySQL, 2nd Edition
Summary (continued)
• When you serialize an object with the
serialize() function, PHP looks in the
object’s class for a special function named
__sleep(), which you can use to perform
many of the same tasks as a destructor function
• When the unserialize() function executes,
PHP looks in the object’s class for a special
function named __wakeup(), which you can
use to perform many of the same tasks as a
constructor function

Weitere ähnliche Inhalte

Was ist angesagt?

Chapter 7 working with databases and my sql
Chapter 7 working with databases and my sqlChapter 7 working with databases and my sql
Chapter 7 working with databases and my sql
kausar31
 
Database Connection With Mysql
Database Connection With MysqlDatabase Connection With Mysql
Database Connection With Mysql
Harit Kothari
 

Was ist angesagt? (20)

Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Chapter 7 working with databases and my sql
Chapter 7 working with databases and my sqlChapter 7 working with databases and my sql
Chapter 7 working with databases and my sql
 
Introduction to php database connectivity
Introduction to php  database connectivityIntroduction to php  database connectivity
Introduction to php database connectivity
 
Sqlmap
SqlmapSqlmap
Sqlmap
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query Optimizations
 
Database Programming
Database ProgrammingDatabase Programming
Database Programming
 
SQLMAP Tool Usage - A Heads Up
SQLMAP Tool Usage - A  Heads UpSQLMAP Tool Usage - A  Heads Up
SQLMAP Tool Usage - A Heads Up
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
 
Database Connection With Mysql
Database Connection With MysqlDatabase Connection With Mysql
Database Connection With Mysql
 
Mule dataweave
Mule dataweaveMule dataweave
Mule dataweave
 
lab56_db
lab56_dblab56_db
lab56_db
 
Sqlmap
SqlmapSqlmap
Sqlmap
 
5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow Basics5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow Basics
 
MYSQL-Database
MYSQL-DatabaseMYSQL-Database
MYSQL-Database
 
Oracle 12c New Features For Better Performance
Oracle 12c New Features For Better PerformanceOracle 12c New Features For Better Performance
Oracle 12c New Features For Better Performance
 
MySQL Replication Evolution -- Confoo Montreal 2017
MySQL Replication Evolution -- Confoo Montreal 2017MySQL Replication Evolution -- Confoo Montreal 2017
MySQL Replication Evolution -- Confoo Montreal 2017
 
Oracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsOracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic Functions
 
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Core Java Programming Language (JSE) : Chapter XIII -  JDBCCore Java Programming Language (JSE) : Chapter XIII -  JDBC
Core Java Programming Language (JSE) : Chapter XIII - JDBC
 

Ähnlich wie 9780538745840 ppt ch10

OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
rani marri
 

Ähnlich wie 9780538745840 ppt ch10 (20)

Php oop (1)
Php oop (1)Php oop (1)
Php oop (1)
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
 
UNIT-IV WT web technology for 1st year cs
UNIT-IV WT web technology for 1st year csUNIT-IV WT web technology for 1st year cs
UNIT-IV WT web technology for 1st year cs
 
CodeIgniter & MVC
CodeIgniter & MVCCodeIgniter & MVC
CodeIgniter & MVC
 
Oop in php lecture 2
Oop in  php lecture 2Oop in  php lecture 2
Oop in php lecture 2
 
Oops in php
Oops in phpOops in php
Oops in php
 
Introduction Php
Introduction PhpIntroduction Php
Introduction Php
 
PHP MYSQL Training in Bangalore
PHP  MYSQL Training in BangalorePHP  MYSQL Training in Bangalore
PHP MYSQL Training in Bangalore
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHP
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Oopsinphp
OopsinphpOopsinphp
Oopsinphp
 
Oop's in php
Oop's in php Oop's in php
Oop's in php
 
PHP- Introduction to Object Oriented PHP
PHP-  Introduction to Object Oriented PHPPHP-  Introduction to Object Oriented PHP
PHP- Introduction to Object Oriented PHP
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 

Mehr von Terry Yoast

Mehr von Terry Yoast (20)

9781305078444 ppt ch12
9781305078444 ppt ch129781305078444 ppt ch12
9781305078444 ppt ch12
 
9781305078444 ppt ch11
9781305078444 ppt ch119781305078444 ppt ch11
9781305078444 ppt ch11
 
9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09
 
9781305078444 ppt ch08
9781305078444 ppt ch089781305078444 ppt ch08
9781305078444 ppt ch08
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07
 
9781305078444 ppt ch06
9781305078444 ppt ch069781305078444 ppt ch06
9781305078444 ppt ch06
 
9781305078444 ppt ch05
9781305078444 ppt ch059781305078444 ppt ch05
9781305078444 ppt ch05
 
9781305078444 ppt ch04
9781305078444 ppt ch049781305078444 ppt ch04
9781305078444 ppt ch04
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03
 
9781305078444 ppt ch02
9781305078444 ppt ch029781305078444 ppt ch02
9781305078444 ppt ch02
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11
 

Kürzlich hochgeladen

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Kürzlich hochgeladen (20)

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 

9780538745840 ppt ch10

  • 1. Chapter 10 Developing Object-Oriented PHP PHP Programming with MySQL 2nd Edition
  • 2. 2PHP Programming with MySQL, 2nd Edition Objectives In this chapter, you will: • Study object-oriented programming concepts • Use objects in PHP scripts • Declare data members in classes • Work with class member functions
  • 3. 3PHP Programming with MySQL, 2nd Edition Introduction to Object-Oriented Programming • Object-oriented programming (OOP) refers the concept of merging related variables and functions into a single interface • An object refers to programming code and data that can be treated as an individual unit or component • Objects are often also called components
  • 4. 4PHP Programming with MySQL, 2nd Edition Introduction to Object-Oriented Programming (continued) • Data refers to information contained within variables or other types of storage structures • The functions associated with an object are called methods • The variables that are associated with an object are called properties or attributes • Popular object-oriented programming languages include C++, Java, and Visual Basic
  • 5. 5PHP Programming with MySQL, 2nd Edition Introduction to Object-Oriented Programming (continued) Figure 10-1 Accounting program
  • 6. 6PHP Programming with MySQL, 2nd Edition Understanding Encapsulation • Objects are encapsulated – all code and required data are contained within the object itself • Encapsulated objects hide all internal code and data • An interface refers to the methods and properties that are required for a source program to communicate with an object
  • 7. 7PHP Programming with MySQL, 2nd Edition Understanding Encapsulation (continued) • Encapsulated objects allow users to see only the methods and properties of the object that you allow them to see • Encapsulation reduces the complexity of the code • Encapsulation prevents other programmers from accidentally introducing a bug into a program, or stealing code
  • 8. 8PHP Programming with MySQL, 2nd Edition Object-Oriented Programming and Classes • The code, methods, attributes, and other information that make up an object are organized into classes • An instance is an object that has been created from an existing class • Creating an object from an existing class is called instantiating the object • An object inherits its methods and properties from a class — it takes on the characteristics of the class on which it is based
  • 9. 9PHP Programming with MySQL, 2nd Edition Using Objects in PHP Scripts • Declare an object in PHP by using the new operator with a class constructor • A class constructor is a special function with the same name as its class that is called automatically when an object from the class is instantiated • The syntax for instantiating an object is: $ObjectName = new ClassName();
  • 10. 10PHP Programming with MySQL, 2nd Edition Using Objects in PHP Scripts (continued) • After an object is instantiated, use a hyphen and a greater-than symbol (->) to access the methods and properties contained in the object • Together, these two characters are referred to as member selection notation • With member selection notation, one or more characters are appended to an object, followed by the name of a method or property
  • 11. 11PHP Programming with MySQL, 2nd Edition Using Objects in PHP Scripts (continued) • With methods, include a set of parentheses at the end of the method name, just as with functions • Like functions, methods can also accept arguments $Checking->getBalance(); $CheckNumber = 1022; $Checking->getCheckAmount($CheckNumber);
  • 12. 12PHP Programming with MySQL, 2nd Edition Working with Database Connections as Objects • Access MySQL database connections as objects by instantiating an object from the mysqli class • To connect to a MySQL database server using procedural syntax: $DBConnect = mysql_connect("php_db", "dongosselin", "rosebud"); mysql_select_db("real_estate", $DBConnect); • To connect to the MySQL database server using object-oriented style: $DBConnect = new mysqli("php_db", "dongosselin", "rosebud", "real_estate");
  • 13. 13PHP Programming with MySQL, 2nd Edition Handling MySQL Errors • This statement uses the mysqli() constructor function to instantiate a mysqli class object named $DBConnect $DBConnect = @new mysqli("php_db", "dgosselin", "rosebud"); • To explicitly close the database connection, use the close() method of the mysqli class $DBConnect->close();
  • 14. 14PHP Programming with MySQL, 2nd Edition Handling MySQL Errors (continued) • With object-oriented style, check whether a value is assigned to the mysqli_connect_errno() or mysqli_connect_error() functions $DBConnect = @new mysqli("php.db", "dgosselin", "rosebud"); if ($DBConnect->connect_errno){ echo("<p>Unable to connect to the database server.</p>" . "<p>Error code " . $DBConnect->connect_errno . ": " . $DBConnect->connect_error. "</p>n"; else { //code to execute if the connection fails }
  • 15. 15PHP Programming with MySQL, 2nd Edition Executing SQL Statements • With object-oriented style, use the query() method of the mysqli class • To return the fields in the current row of a resultset into an indexed array use: – The fetch_row() method of the mysqli class • To return the fields in the current row of a resultset into an associative array use: – The fetch_assoc() method of the msqli class
  • 16. 16PHP Programming with MySQL, 2nd Edition Executing SQL Statements (continued) $TableName = "company_cars"; $SQLstring = "SELECT * FROM $TableName"; $QueryResult = @$DBConnect->query($SQLstring); if ($QueryResult === FALSE) echo "<p>Unable to execute the query. " . "Error code " . $DBConnect->errno . ": " . $DBConnect->error . "</p>n"; else { echo "<table width='100%' border='1'>n"; echo "<tr><th>License</th><th>Make</th><th>Model</th>" . "<th>Mileage</th><th>Year</th></tr>n";
  • 17. 17PHP Programming with MySQL, 2nd Edition Executing SQL Statements (continued) … while (($Row = $QueryResult->fetch_row()) !== FALSE) { echo "<tr><td>{$Row[0]}</td>"; echo "<td>{$Row[1]}</td>"; echo "<td>{$Row[2]}</td>"; echo "<td align='right'>{$Row[3]}</td>"; echo "<td>{$Row[4]}</td></tr>n"; } echo "</table>n"; }
  • 18. 18PHP Programming with MySQL, 2nd Edition Defining Custom PHP Classes • Data structure refers to a system for organizing data • The functions and variables defined in a class are called class members • Class variables are referred to as data members or member variables • Class functions are referred to as member functions or function members
  • 19. 19PHP Programming with MySQL, 2nd Edition Defining Custom PHP Classes (continued) • Classes: – Help make complex programs easier to manage – Hide information that users of a class do not need to access or know about – Make it easier to reuse code or distribute your code to others for use in their programs • Inherited characteristics allow you to build new classes based on existing classes without having to rewrite the code contained in the existing one
  • 20. 20PHP Programming with MySQL, 2nd Edition Creating a Class Definition • To create a class in PHP, use the class keyword to write a class definition • A class definition contains the data members and member functions that make up the class • The syntax for defining a class is: class ClassName { data member and member function definitions }
  • 21. 21PHP Programming with MySQL, 2nd Edition Creating a Class Definition (continued) • The ClassName portion of the class definition is the name of the new class • Class names usually begin with an uppercase letter to distinguish them from other identifiers • Within the class’s curly braces, declare the data type and field names for each piece of information stored in the structure class BankAccount { data member and member function definitions } $Checking = new BankAccount();
  • 22. 22PHP Programming with MySQL, 2nd Edition Creating a Class Definition (continued) • Class names in a class definition are not followed by parentheses, as are function names in a function definition $Checking = new BankAccount(); echo 'The $Checking object is instantiated from the ' . get_class($Checking) . " class.</p>"; • Use the instanceof operator to determine whether an object is instantiated from a given class • Use the class_exists() to determine if a class exists
  • 23. 23PHP Programming with MySQL, 2nd Edition Storing Classes in External Files • PHP provides the following functions that allow you to use external files in your PHP scripts: – include() – require() – include_once() – require_once() • You pass to each function the name and path of the external file you want to use
  • 24. 24PHP Programming with MySQL, 2nd Edition Storing Classes in External Files (continued) • include() and require() functions both insert the contents of an external file, called an include file, into a PHP script • include_once() and require_once() functions only include an external file once during the processing of a script • Any PHP code must be contained within a PHP script section (<?php ... ?>) in an external file
  • 25. 25PHP Programming with MySQL, 2nd Edition Collecting Garbage • Garbage collection refers to cleaning up or reclaiming memory that is reserved by a program • PHP knows when your program no longer needs a variable or object and automatically cleans up the memory for you • The one exception is with open database connections
  • 26. 26PHP Programming with MySQL, 2nd Edition Information Hiding • Information hiding states that any class members that other programmers, sometimes called clients, do not need to access or know about should be hidden • Helps minimize the amount of information that needs to pass in and out of an object • Reduces the complexity of the code that clients see • Prevents other programmers from accidentally introducing a bug into a program by modifying a class’s internal workings
  • 27. 27PHP Programming with MySQL, 2nd Edition Using Access Specifiers • Access specifiers control a client’s access to individual data members and member functions • There are three levels of access specifiers in PHP: public, private, and protected • The public access specifier allows anyone to call a class’s member function or to modify and retrieve a data member
  • 28. 28PHP Programming with MySQL, 2nd Edition Using Access Specifiers (continued) • The private access specifier prevents clients from calling member functions or accessing data members and is one of the key elements in information hiding • Private access does not restrict a class’s internal access to its own members • Private access restricts clients from accessing class members
  • 29. 29PHP Programming with MySQL, 2nd Edition Using Access Specifiers (continued) • Include an access specifier at the beginning of a data member declaration statement class BankAccount { public $Balance = 0; } • Always assign an initial value to a data member when you first declare it class BankAccount { public $Balance = 1 + 2; }
  • 30. 30PHP Programming with MySQL, 2nd Edition Serializing Objects • Serialization refers to the process of converting an object into a string that you can store for reuse • Serialization stores both data members and member functions into strings • To serialize an object, pass an object name to the serialize() function $SavedAccount = serialize($Checking);
  • 31. 31PHP Programming with MySQL, 2nd Edition Serializing Objects (continued) • To convert serialized data back into an object, you use the unserialize() function $Checking = unserialize($SavedAccount); • Serialization is also used to store the data in large arrays • To use serialized objects between scripts, assign a serialized object to a session variable session_start(); $_SESSION('SavedAccount') = serialize($Checking);
  • 32. 32PHP Programming with MySQL, 2nd Edition Working with Member Functions • Create public member functions for any functions that clients need to access • Create private member functions for any functions that clients do not need to access • Access specifiers control a client’s access to individual data members and member functions
  • 33. 33PHP Programming with MySQL, 2nd Edition Working with Member Functions (continued) class BankAccount { public $Balance = 958.20; public function withdrawal($Amount) { $this->Balance -= $Amount; } } if (class_exists("BankAccount")) $Checking = new BankAccount(); else exit("<p>The BankAccount class is not available!</p>"); printf("<p>Your checking account balance is $%.2f.</p>", $Checking->Balance); $Cash = 200; $Checking->withdrawal(200); printf("<p>After withdrawing $%.2f, your checking account balance is $%.2f.</p>", $Cash, $Checking->Balance);
  • 34. 34PHP Programming with MySQL, 2nd Edition Using the $this Reference • Outside of a class, refer to the members of the object using the name of the object, the member selection nation (-), and the name of the function or variable • Within a class function definition, use $this to refer to the current object of the class $this->AccountNumber = 0;
  • 35. 35PHP Programming with MySQL, 2nd Edition Initializing with Constructor Functions • A constructor function is a special function that is called automatically when an object from a class is instantiated class BankAccount { private $AccountNumber; private $CustomerName; private $Balance; function __construct() { $this->AccountNumber = 0; $this->Balance = 0; $this->CustomerName = ""; } }
  • 36. 36PHP Programming with MySQL, 2nd Edition Initializing with Constructor Functions (continued) • The __construct() function takes precedence over a function with the same name as the class • Constructor functions are commonly used in PHP to handle database connection tasks
  • 37. 37PHP Programming with MySQL, 2nd Edition Cleaning Up with Destructor Functions • A default constructor function is called when a class object is first instantiated • A destructor function is called when the object is destroyed • A destructor function cleans up any resources allocated to an object after the object is destroyed
  • 38. 38PHP Programming with MySQL, 2nd Edition Cleaning Up with Destructor Functions (continued) • A destructor function is commonly called in two ways: – When a script ends – When you manually delete an object with the unset() function • To add a destructor function to a PHP class, create a function named __destruct()
  • 39. 39PHP Programming with MySQL, 2nd Edition Cleaning Up with Destructor Functions (continued) function __construct() { $DBConnect = new mysqli("php_db", "dongosselin","rosebud", "real_estate"); } function __destruct() { $DBConnect->close(); }
  • 40. 40PHP Programming with MySQL, 2nd Edition Writing Accessor Functions • Accessor functions are public member functions that a client can call to retrieve or modify the value of a data member • Accessor functions often begin with the words “set” or “get” • Set functions modify data member values • Get functions retrieve data member values
  • 41. 41PHP Programming with MySQL, 2nd Edition Writing Accessor Functions (continued) class BankAccount { private $Balance = 0; public function setBalance($NewValue) { $this->Balance = $NewValue; } public function getBalance() { return $this->Balance; } } if (class_exists("BankAccount")) $Checking = new BankAccount(); else exit("<p>The BankAccount class is not available!</p>"); $Checking->setBalance(100); echo "<p>Your checking account balance is " . $Checking->getBalance() . "</p>n";
  • 42. 42PHP Programming with MySQL, 2nd Edition Serialization Functions • When you serialize an object with the serialize() function, PHP looks in the object’s class for a special function named __sleep() • The primary reason for including a __sleep() function in a class is to specify which data members of the class to serialize
  • 43. 43PHP Programming with MySQL, 2nd Edition Serialization Functions (continued) • If you do not include a __sleep() function in your class, the serialize() function serializes all of its data members function __sleep() { $SerialVars = array('Balance'); return $SerialVars; } • When the unserialize() function executes, PHP looks in the object’s class for a special function named __wakeup()
  • 44. 44PHP Programming with MySQL, 2nd Edition Summary • The term “object-oriented programming (OOP)” refers to the creation of reusable software objects that can be easily incorporated into multiple programs. The term “object” specifically refers to programming code and data that can be treated as an individual unit or component (object) • The term “data” refers to information contained within variables or other types of storage structures
  • 45. 45PHP Programming with MySQL, 2nd Edition Summary (continued) • The functions associated with an object are called methods, and the variables associated with an object are called properties or attributes • Objects are encapsulated, which means that all code and required data are contained within the object itself • An interface represents elements required for a source program to communicate with an object
  • 46. 46PHP Programming with MySQL, 2nd Edition Summary (continued) • In object-oriented programming, the code, methods, attributes, and other information that make up an object are organized into classes • An instance is an object that has been created from an existing class. When you create an object from an existing class, you are “instantiating the object”
  • 47. 47PHP Programming with MySQL, 2nd Edition Summary (continued) • A particular instance of an object inherits its methods and properties from a class—that is, it takes on the characteristics of the class on which it is based • A constructor is a special function with the same name as its class; it is called automatically when an object from the class is instantiated • The term “data structure” refers to a system for organizing data
  • 48. 48PHP Programming with MySQL, 2nd Edition Summary (continued) • The functions and variables defined in a class are called class members. Class variables are referred to as data members or member variables, whereas class functions are referred to as member functions or function members • A class definition contains the data members and member functions that make up the class
  • 49. 49PHP Programming with MySQL, 2nd Edition Summary (continued) • PHP provides the following functions that allow you to use external files in your PHP scripts: include(), require(), include_once(), and require_once() • The principle of information hiding states that class members should be hidden when other programmers do not need to access or know about them • Access specifiers control a client’s access to individual data members and member functions
  • 50. 50PHP Programming with MySQL, 2nd Edition Summary (continued) • Serialization refers to the process of converting an object into a string that you can store for reuse • A constructor function is a special function that is called automatically when an object from a class is instantiated • A destructor function cleans up any resources allocated to an object after the object is destroyed
  • 51. 51PHP Programming with MySQL, 2nd Edition Summary (continued) • Accessor functions are public member functions that a client can call to retrieve the value of a data member • Mutator functions are public member functions that a client can call to modify the value of a data member
  • 52. 52PHP Programming with MySQL, 2nd Edition Summary (continued) • When you serialize an object with the serialize() function, PHP looks in the object’s class for a special function named __sleep(), which you can use to perform many of the same tasks as a destructor function • When the unserialize() function executes, PHP looks in the object’s class for a special function named __wakeup(), which you can use to perform many of the same tasks as a constructor function