0% found this document useful (0 votes)
8 views47 pages

PHP - Part3

The document provides an overview of Object-Oriented Programming (OOP) in PHP, covering the creation and manipulation of objects, classes, and their components such as constructors and destructors. It explains how to define classes, instantiate objects, and utilize member functions and variables, including private and static members. Additionally, it discusses the inclusion of external files, predefined objects, and handling MySQL database connections using OOP principles in PHP.

Uploaded by

tekbwoy1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views47 pages

PHP - Part3

The document provides an overview of Object-Oriented Programming (OOP) in PHP, covering the creation and manipulation of objects, classes, and their components such as constructors and destructors. It explains how to define classes, instantiate objects, and utilize member functions and variables, including private and static members. Additionally, it discusses the inclusion of external files, predefined objects, and handling MySQL database connections using OOP principles in PHP.

Uploaded by

tekbwoy1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 47

Object-Oriented Programming

Today's Goals
Today we will begin with a discussion on
objects in PHP including how to create
instances and custom objects.
Object-Oriented Programming.
This will be followed by a discussion of
XAMP/WAMP environment.
Objects in PHP
The concept of objects is the same across
different object-oriented programming
languages.
There are, however, minor differences in
how a programmer references objects
using PHP.
Creating a New PHP Object
Instance
Just like JavaScript, PHP uses the keyword
"new" to create a new instance of an object.
Example: $_myinstance = new
Object(args);
Syntax elements:
Just like variables, the name used to identify
the instance needs to begin with '$'.
Many objects need arguments (the "args" part
of the above example) in order to create a new
instance. These are passed to a function
called a constructor which initializes the
instance.
Referring to Components of a PHP
Instance
In JavaScript, we used periods (.) to
delimit/separate the elements of an object
hierarchy. For example:
document.writeln("Hello, World!");
In PHP, the operator "->" is used to delimit/separate
the elements of an object hierarchy. For example:
$object_name->object_function();
The above example refers to a function (note the
parenthesis). The same format is used for
properties too, i.e.,
$object_name-> property;
Defining a Class

A class is the definition used to create an


instance.
A class definition defines the class' name, its
variables, and functions.
A class definition can also contain functions used
to initialize instances (constructors) and remove
them (destructors).
Format of a Class Definition
<?php
// Basic format of a class definition

class ClassName
{
// Member variables
var $_variable1 = 0;
var $_variable2 = "String";

// Member functions
function classFunction($_arg1 = 0, $_arg2)
{
// Function code goes here
}
}
?>
Format of a Class Definition
(continued)
The keyword "class" followed by the class
name is used to start the definition. Curly
brackets are used to enclose all of the
elements of the definition.
The keyword "var" is used to identify the
class' variables.
Variables can be initialized. Every time a
new instance is created, the variables for
that instance are initialized to these values.
Functions are defined normally, but when
contained within the curly brackets of the
class, become member functions of the class.
Private Member Variables
There are some cases when a class may not
want to have its variables accessible outside of
the class
Variables may be set up only for internal use within
the class' functions
Variables may have certain restrictions on values that
must be enforced internally
If a variable needs to be modified from outside
the class, a function can be provided to do so.
For example, instead of:
$_instance -> variable1 = 25;
use
$_instance -> updateVariable1(25);
Private Member Variables
To declare a variable as private, simply replace the
keyword "var" with the keyword "private" in the
variable declaration.
Example:
private $_variable3 = 4.0;
A class can also have private member functions. In
this case, declare the function by putting the
keyword "private" in front of the function
declaration.
Private variables became available with PHP 5.
Static Member Variables
Each time an instance of a class is created, a
whole new set of variables and functions for that
instance is created along with it.
It is possible to make it so that regardless of the
number of instances of a class, only a single
variable is created for that class.
This allows all instances to share a single variable.
To do this, replace the keyword "var" with the
keyword "static" in the variable declaration.
Static variables became available with PHP 5.
Constructors
A function can be written for a class that is
automatically called whenever an instance for
that class is created. This is called a constructor.

When an instance is created, it may be necessary


to go through an initialization process.
This initialization process might be based on
arguments passed from the code creating the
instance.
Constructors (continued)

A constructor has the same format as a


regular function except for the name.
The name of a constructor in PHP 5 is
_ _construct(). (In PHP 4 it has the same
name as the class.)
Example:
function _ _construct($_arg = 0)
{
// Code to initialize class
}
Note: I have put a space between the
underscores to show there are two of them.
No space is used.
Destructors
It is also possible that some housekeeping or
cleanup needs to be performed when an instance
is removed.
In this case, a destructor function is automatically
called to close the instance.
Destructors are only available in PHP 5.
Unlike the constructor function, no arguments can
be passed to the destructor function.
The name of a destructor is always
_ _destruct().
Class Definition Example
class Person
{
var $full_name;
var $birthday;
var $gender;

// Print function to output person's data in HTML


function printPersonInHTML()
{
print "<p>{$this->full_name} is a ";
if(($this->gender == 'M')||($this->gender == 'm'))
print "male";
else
print "female";
print
" who was born on {$this->birthday}.</p>";
}

// Class continued on next slide


(continued)
// Constructor for PHP 5
function _ _construct($first_name, $last_name,
$gender, $birth_month,
$birth_day, $birth_year)
{
$month_list = array ("January", "February",
"March", "April", "May", "June",
"July", "August", "September",
"October", "November", "December");
$this->full_name = $first_name." ".$last_name;
$this->birthday =
$month_list[$birth_month-1]." ".
$birth_day.", ". $birth_year;
$this->gender = $gender;
}
}
Class Definition Example
(continued)
The code to create an instance and call the
class function printPersonInHTML() looks
like this:
$person_1 = new Person("John",
"Doe", "m", 3, 24, 1974);
$person_1 -> printPersonInHTML();
The output then will be:

John Doe is a male who was born on


March 24, 1974.
Include Files in PHP
Reasons to include or import an external file into a PHP
file.
Allows sharing of common resources among multiple PHP files.
Simplifies a PHP file by encapsulating functionality.

PHP uses a set of functions to include a file into a


script. (Note that since these functions are part of the
language construct, parenthesis are not required.)
include(URL_str) – includes the file referenced by URL_str
require(URL_str) – same as include() except that an error
during the include is fatal and will stop processing
include_once(URL_str) – same as include() except that a
second include() is ignored.
require_once(URL_str) – same as require() except that a
second require() is ignored.
Include Files in PHP
(continued)
Examples:
<?php
require_once("file.php");
include 'file.php';
include
'http://www.mydomain.com/file.php';
?>

Note that it is important to have the extension .php


on your included files. This forces them to be
processed with the PHP engine before sending it to
a client. It is a security issue.
PHP Predefined Objects
As with other languages, PHP has a number of
predefined objects and functions that provide
access to system resources.
One package containing these objects and
functions is called the PHP Extension and
Application Repository or PEAR.
It includes support for:
•Web services •Data validation
•Image processing •Database access
•File handling •Payment processing

• PEAR was originally designed to support scripting for


HTML such as providing templates for documents and
platform independence.
Object-Oriented Programming
Object-oriented programming (OOP)
refers to the creation of reusable software
objects that can be easily incorporated into
multiple programs
An object refers to programming code and
data that can be treated as an individual
unit or component
Objects are often also called components

21 PHP-Object Oriented Programming


Object-Oriented Programming
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

22 PHP-Object Oriented Programming


Object-Oriented Programming

Figure 11-1 Accounting program

23 PHP-Object Oriented Programming


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

24 PHP-Object Oriented Programming


Understanding Encapsulation
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

25 PHP-Object Oriented Programming


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

26 PHP-Object Oriented Programming


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();

27 PHP-Object Oriented Programming


Using Objects in PHP Scripts
The identifiers for an object name:
Must begin with a dollar sign
Can include numbers or an underscore
Cannot include spaces
Are case sensitive
$Checking = new BankAccount();
Can pass arguments to many constructor
functions
$Checking = new BankAccount(01234587, 1021, 97.58);

28 PHP-Object Oriented Programming


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 append one
or more characters to an object, followed by
the name of a method or property

29 PHP-Object Oriented Programming


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);

30 PHP-Object Oriented Programming


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:
$DBConnect = mysqli_connect("localhost",
"dongosselin", "rosebud", "real_estate");
To connect to the MySQL database server using
object-oriented style:
$DBConnect = new mysqli("localhost", "dongosselin",
"rosebud", "real_estate");

31 PHP-Object Oriented Programming


Instantiating and Closing a
MySQL Database Object
This statement also uses the mysqli()
constructor function to instantiate a mysqli
class object named $DBConnect
$DBConnect = new mysqli("localhost",
"dongosselin","rosebud", "real_estate");
To explicitly close the database connection,
use the close() method of the mysqli
class
$DBConnect->close();

32 PHP-Object Oriented Programming


Selecting a Database
Select or change a database with the
mysqli_select_db() function
Pass two arguments to the
mysqli_select_db() function:
1. The variable representing the database
connection
2. The name of the database you want to use

33 PHP-Object Oriented Programming


Selecting a Database
(continued)
Example of procedural syntax to open a
connection to a MySQL database server:
$DBConnect = mysqli_connect("localhost", "dongosselin",
"rosebud");
mysqli_select_db($DBConnect, "real_estate");
// additional statements that access or manipulate the database
mysqli_close($DBConnect);
An object-oriented version of the code:
$DBConnect = mysqli_connect("localhost", "dongosselin",
"rosebud");
$DBConnect->select_db("real_estate");
// additional statements that access or manipulate the database
$DBConnect->close();

34 PHP-Object Oriented Programming


Handling MySQL Errors
With object-oriented style, you cannot
terminate script execution with the die() or
exit() functions
$DBConnect = @mysqli_connect("localhost", "dongosselin",
"rosebud")
Or die("<p>Unable to connect to the database server.</p>"
. "<p>Error code " . mysqli_connect_errno()
. ": " . mysqli_connect_error()) . "</p>";

35 PHP-Object Oriented Programming


Handling MySQL Errors
With object-oriented style, check whether a
value is assigned to the
mysqli_connect_errno() or
mysqli_connect_error() functions and then
call the die() function to terminate script
execution
$DBConnect = @new mysqli("localhost", "dgosselin",
"rosebud");
if (mysqli_connect_errno())
die("<p>Unable to connect to the database
server.</p>"
. "<p>Error code " . mysqli_connect_errno()
. ": " . mysqli_connect_error()) . "</p>";

36 PHP-Object Oriented Programming


Handling MySQL Errors
For any methods of the mysqli class
that fail (as indicated by a return value
of false), terminate script execution by
appending die() or exit() functions
to method call statements
$DBName = "guitars";
@$DBConnect->select_db($DBName)
Or die("<p>Unable to select the database.</p>"
. "<p>Error code " . mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)) . "</p>";

37 PHP-Object Oriented Programming


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 mysqli_fetch_row() function
To return the fields in the current row of a
resultset into an associative array use:
The mysqli_fetch_assoc() function

38 PHP-Object Oriented Programming


Executing SQL Statements
(continued)
$TableName = "inventory";
$SQLstring = "SELECT * FROM inventory";
$QueryResult = $DBConnect->query($SQLstring)
Or die("<p>Unable to execute the query.</p>"
. "<p>Error code “ . $DBConnect->errno
. ": “ . $DBConnect->error) . "</p>";
echo "<table width='100%‘ border='1'>";
echo "<tr><th>Make</th><th>Model</th>
<th>Price</th><th>Inventory</th></tr>";
$Row = $QueryResult->fetch_row();
do {
echo "<tr><td>{$Row[0]}</td>";
echo "<td>{$Row[1]}</td>";
echo "<td align='right'>{$Row[2]}</td>";
echo "<td align='right'>{$Row[3]}</td></tr>";
$Row = $QueryResult->fetch_row();
} while ($Row);

39 PHP-Object Oriented Programming


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

40 PHP-Object Oriented Programming


Defining Custom PHP Classes
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

41 PHP-Object Oriented Programming


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
}

42 PHP-Object Oriented Programming


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();

43 PHP-Object Oriented Programming


Creating a Class Definition
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

44 PHP-Object Oriented Programming


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

45 PHP-Object Oriented Programming


Storing Classes in External
Files
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

46 PHP-Object Oriented Programming


Storing Classes in External
Files
Use the include() and include_once()
functions for files that will not prevent the
application from running
Use the require() or require_once()
functions for files that will prevent the app
from running if not present
External files can be used for classes and for
any type of PHP code or HTML code that you
want to reuse on multiple Web pages
You can use any file extension you want for
include files

47 PHP-Object Oriented Programming

You might also like