As you can see in Figure 17.1, a class is a unit consisting of a name for the class, in this case House, the variables that describe the house, and the methods that describe the behavior
Trang 14 <input type="password" name="password">< br />
5 <input type="hidden" name="login">< br />
<input type="submit"> <input type="reset">
Trang 2Figure 16.37 Page 1: The visitor fills out the form
Trang 4<h2>You are not logged in</h2>
<p>Hello Since you are not logged in, you cannot view protected content</p>
5 <p>But you can <a href="login.html">log in</a></p>
Trang 5Figure 16.38 Page 3: The visitor is logged in
16.5 Chapter Summary
In this chapter we discussed how PHP uses cookies and sessions to maintain state; that is, save information between different accesses to a Web page, allowing you to customize your applications based on user preferences, manage logging in and out of your site, use links and hidden fields to pass session information back and forth, and so on What are the pros and cons of cookies versus sessions and vice versa? The cookie stores the visitor information on the user’s computer even if a session has ended The the lifetime of a cookie can be a long period of time or it can end when the user closes his or her browser A user can go to a Web site, browse around and come back, even log out and the cookie can persist on his or her hard drive, keeping track of the user’s preferences, shopping cart information, number
of times he or she visited the site, and so on But if the cookie has important information such as a password or user ID,
it is easy to read that information unless it is encrypted, and some people feel that cookies are a security threat because they are passed back and forth across the network and are stored in a text-based readable files Because a user can disable cookies for his or her particular browser, you have no guarantee that they are being accepted
PHP sessions are safer because they do not send any sensitive data over the network They store the user information in variables on the server As you have seen in this chapter, even sessions rely on cookies because the session ID is encrypted and normally passed in a cookie, but there are alternative ways to handle users who have disabled cookies for their browser, such as passing the data in hidden form fields or URLs Although this is considered insecure, you can regenerate the session ID after using it or destroy all the session variables The lifespan of sessions is normally the length of a session, and after 24 minutes, the session files are deleted, but this can also be controlled in the php.ini file What if you have a cluster of servers? How will the session files be managed? At least with a cookie, only one browser is necessary, no matter how many servers are involved Which is best?
It has been said that over 90 percent of sessions use cookies, so perhaps a symbiotic relationship between the two is a reasonable approach Ultimately, you must weigh the pros and cons and decide what works best for you (See
http://www.thescripts.com/forum/thread433783.html for further discussion.)
Trang 616.5.1 What You Should Know
Now that you have finished this chapter you should be able to answer the following questions:
Trang 7Chapter 16 Lab
1
actionverify.php
Trang 8Chapter 17 Objects
17.1 What Are Objects?
Objects are things we deal with every day PHP deals with objects, as do most programming languages, and these
languages are called object-oriented programming (OOP) OOP is a way of trying to solve a problem in terms of world objects Some people are apprehensive at the thought of tackling this kind of programming, and are perfectly happy
real-to stick with real-top-down, procedural programs Just as the everyday objects we use are not switchblades and hacksaws, neither are programming objects They are just a way of representing data
As PHP has evolved from a tool for building simple home pages to a language for serious Web development, so has its support for OOP Once programs start to get larger and more complex, planning and design become more important Think of a simple home page put together with some family photos, links, and blogs Then think of a Web site like Amazon or eBay where there are thousands of forms, links, and transactions taking place all the time, all over the world—the thought of putting something like that together is staggering OOP is best suited to manage the complexity of such large Web sites Even if you do not program using objects, if you are reading and using PHP programs written by other programmers, you are bound to run into this style of programming This chapter gently introduces you to PHP objects and some of the features that have been added to the language in PHP 5
When talking about PHP data types in Chapter 4, “The Building Blocks,” we discussed two types: primitive types and composite types Like arrays, objects are composite types They provide a way to organize a collection of data into a single unit Object-oriented languages, such as C++ and Java, bundle up data into a variable and call it an object So does PHP Each object-oriented language you encounter is based on the same principles, but often the terminology is not exactly the same when describing the concepts You could say that PHP is like Java and C++, but has its own way of dealing with objects
When you learn about objects, they are usually compared to real-world things, like a black cat, a modern painting, or a green pillow Using the English language to describe an object, the object itself would be like a noun: a person, place, or thing
Nouns are described with adjectives For the cat it might be described as fat and furry with green eyes, four legs, and a tail; the painting is a British frigate, oil on canvas, and sells for $52,000; and the pillow is green silk, square, with dimensions
of 18″ × 18″ The adjectives that collectively describe these objects are called the properties (or attributes) of the object The object is made up of a collection of these properties
In English, verbs are used to describe what the object can do or what can be done to it The cat eats and sleeps, and its tail twitches; the painting can be framed, sold, or purchased; the pillow’s dimensions can be increased or decreased, its fabric and color changed, and so on These verbs are functions called methods in object-oriented languages
17.1.1 Objects and Classes
Objects are defined in a class A class is a template or a blueprint that defines what an object should look like and what it can do A class represents a group of similar objects, such as a class of employees, a class of hotels, or a class of cars The object in a class is a concrete person, place, or thing Like a cookie cutter, a class gives an object its form, and as with a cookie cutter, you can build many objects of the same class The employee object might be described to have a name, address, and phone number Although the object can later change its values, it still belongs to the same class You can change Bob’s phone number, but he is still in the employee class You can change the color of the car, but it is still in the car class
A class contains a collection of variables (properties) and functions (methods) Like a blueprint, by itself the class does nothing It defines an object and its properties and methods Properties describe the object Methods are functions that determine the behavior of the object; that is, what kind of actions can be performed on or by the object As you can see in Figure 17.1, a class is a unit consisting of a name for the class, in this case House, the variables that describe the house, and the methods that describe the behaviors of the object, or what it can do A class is an aggregate or composite data type Like an array that contains a collection of key–value pairs, the class represents a collection of properties and methods
Trang 9Figure 17.1 A House class
17.2 Working with Classes
17.2.1 Defining the Class
paintHouse()
Trang 1017.2.2 Instantiating the Class
$yourhouse = new House;
Figure 17.2 Instantiating the House class
The Properties and Methods
var
var public
var $owner = "John Doe:;
var $address;
Trang 11$owner = "John Doe"; // Default is public
$myhouse
$myhouse->address="14 Main St.";
showHouse()
$myhouse->showHouse();
Trang 12Figure 17.3 A House class and creating a house object and accessing it
The gettype() and get_class() Functions
gettype() get_class()
gettype()
new get_class()
Table 17.1 PHP Built-In Class Functions
get_class() Returns the name of the class
of an object
string get_class([object obj])
get_class_vars() Returns an associative array
of public properties
arrayget_class_vars(string class_name)
get_declared_classes() Returns an array of classes
defined in the current script
array get_declared_classes(void)
get_object_vars() Returns an array of
properties for an object
array get_object_vars(object obj)
get_parent_class() Returns the name of the
parent class for the class or object
string get_parent_class([mixed obj])
gettype() Returns the data type of a
variable; if an object is given, returns “object.”
string gettype(mixed var)
Trang 13Table 17.1 PHP Built-In Class Functions
instanceof (PHP 5) A type operator that has
replaced is_a()
instanceof classname
interface_exists() Returns true if an interface
has been defined
bool interface_exists(string interface_name [, bool autoload]) is_a() Returns true if the object is
of this class or this class is its parent
bool is_a(object object, string class_name)
is_subclass_of() Returns true if object has this
class as one of its parents
bool is_subclass_of(mixed object, string class_name)
method_exists() Returns true if this method
exists
bool method_exists(object object, string method_name)
property_exists() Returns true if property
exists in the class and is accessible
bool property_exists(mixed class, string property)
Example 17.1
<?php
# PHP5 Simple class
1 class House{ // Declare a class
2 public $owner=" John"; // Create class variables/properties
public $address="Anywhere, USA";
3 function displayHouse(){
4 echo "This house if of type ", gettype($this),".<br>\n";
5 echo "It belongs to the ", get_class($this),
" class.<br>\n";
6 echo "This house is owned by $this->owner ";
echo "It's address is $this->address.\n<br>";
}
}
// Using the class
7 $myHouse= new House(); // Create an ojbect
8 $myHouse->displayHouse();
?>
Explanation
1 A House class is declared
2 The variables for the House class, called properties, are $owner and $address Both properties
have been assigned inital string values
3 A function for the House class is declared Functions within classes are called methods
4 The gettype() built-in function returns the data type of $this Because $this represents the
current object, the type returned is “object.” See the output in Figure 17.4
5 The get_class() function returns the name of the class to which the object represented by $this
belongs
Trang 146 The value of the object’s property $owner is displayed
7 A new object is created with its own properties defined in the class
8 After creating the new object, the displayHouse() method displays its properties
Figure 17.4 A simple class
17.2.3 Creating a Complete Class
Now that we have defined some of the pieces involved in creating a class, we will build one from scratch The following example defines an Employee class and then creates some objects of that class To see a diagram of the class, see Figure 17.5
Trang 15Figure 17.5 The Employee class and how it is used
Example 17.2
Code View:
<?php
// Defining the Class
1 class Employee { // Define the class
2 public $name; // The properties/attributes
Trang 16}
}
// User of the class
6 $Heidi = new Employee(); // Create a new object
7 $Heidi->name = "Heidi Clum"; // Assign properties
8 $Heidi->address = "1234 Somewhere Blvd ";
9 $Heidi->phone = "123-456-7890";
10 $Brad = new Employee(); // Create another object
11 $Brad->name = "Brad Bit";
1 A class called Employee is declared The class definition is enclosed within curly braces
2–4 The variables, called properties, belonging to this class are defined These properties are declared
public meaning they are visible throughout your script The var keyword is used for backward compatibility with PHP 4, but both public and var are now acceptable
5 This is a function, called a method, defined for the class
6 A new object is created for the class Employee and assigned to a variable called $Heidi The
$Heidi object is allocated its own copies of the properties defined within the Employee class
7–9 To assign values to the properties of the object, the object is followed by an arrow and the property
name $Heidi is an object of class Employee and thus has variables name, address, and phone
10 We declare another object of type Employee and this time assign it to variable $Brad Although
$Heidi and $Brad are both of class Employee, they have different values for the properties name, address, and phone
11–
13
Values are assigned to the properties of object $Brad
14 The method, printPersonInfo(), applies to the object, $Heidi The object is the noun, the
method is the verb It is the action that is taking place on the object The method is called by appending the object with the arrow operator and the name of the method By doing this PHP knows which object in the class this method applies to The method’s function is to print out the properties for the current object, in this case $Heidi Because it is accessing the data for the object, an instance of the class, the method is called an “access” method or an “instance” method
15 Similarly, for the object $Brad, the printPersonInfo() method is called and it will print
values specific to the $Brad object
17.2.4 Displaying an Object
In Chapter 8, “Arrays,” we used the PHP built-in function print_r() to see the contents of an array Now you can use it
to view the contents of an object In the previous example the output of print_r() would be:
Employee Object
(
[name] => Heidi Clum
Trang 1717.2.5 Functions for Getting Class Information
PHP provides a set of built-in functions that will return information about your class and its objects Table 17.1 provides a list of these functions For a complete list and examples of how these methods are used, see
http://us3.php.net/manual/en/ref.classobj.php
17.2.6 Encapsulation and Information Hiding
Encapsulation and information hiding are closely related terms you will hear often in the object-oriented world We use encapsulation when combining the properties and methods to make a class By encapsulating the data in the class, the details of the class can be hidden from the user When we created ordinary functions, the instructions were encapsulated within the function definition When you call a function, you do not know all the details of how it works, you just need to know how to call it, what arguments to pass, and what it returns When you create an object, you must know how to use its methods to access it The details of the object are encapsulated within the class
Information hiding is obscuring the details of the class from the user In the previous example, the Employee class gave Heidi her own name, phone, and address However, Heidi’s information was “public” in scope It could be directly accessed from outside the class The user of the class could change Heidi’s address and phone number What if you do not want anyone to change Heidi’s address or phone number? Often you have objects in which you do not want to allow direct access to the object’s variables For example, a bank account object might have a variable representing the account balance This data should not be available to anyone outside the class, and to access it, the user should use methods provided specifically for that purpose Methods such as makeDeposit(), makeWithdrawal(), and
getBalance() should be the only way to manipulate the account balance, similar in the real world to using an ATM machine In the object-oriented world, you will often hear the phrase, “Access private data with public functions.”
Key principles of OOP are encapsulation and information hiding; that is, combining methods and properties into a class and keeping the class variables hidden from direct access by the class user Data hiding helps to protect the object’s data from being corrupted, and if the class implementation is modified, this should not affect the way the class is used; just as when you have the oil changed in your car, you do not change the way you see the car or how you drive it
17.2.7 Class Members and Scope
The term members refers to the properties and methods of a class, and the term scope refers to where the members can be accessed within the program Properties and methods are prefaced with a scope descriptor, such as public, private, or protected If a member is not prefaced by a scope descriptor, it is considered to be public You should always specify a scope descriptor for properties
Public Scope
Public scope is the default scope for all properties and methods of an object Public means that class members can be accessed from everywhere in the script and are not restricted to the class In Example 17.2 the name, address, and phone properties were public From anywhere within the script, the value of those properties could be changed As stated earlier
in this chapter, prior to PHP 5, the descriptor was var; now you would use public Methods themselves do not require the descriptor and are public by default
Private Scope
Private members are visible or accessible only in the class that defines them They are not directly accessible outside the class or to subclasses (classes derived from the current class; see “Inheritance” on page 763) If you create private
variables, then public methods are used to manipulate the data In the following example, the three variables of the
Employee class are declared private It is not possible for some part of the program outside the class to change or manipulate the values of these variables—a good thing In Example 17.2 if the properties had been declared private, the only way that the object’s properties could have been changed would be through its methods
Trang 18Protected Scope
If you create a new class from an existing class, the private members will not be available to the new class Protected members are available to the class where they are created and to any subclasses (see “Inheritance” on page 763)
Example Using Private Scope
The following example includes a BankAccount class The only property is the balance that is marked private The only way this balance can be changed from a user from outside the class is through its public methods This example hides the balance from the user The properties and methods are encapsulated within the BankAccount class
function makeDeposit( $amount ) {
3 $this->balance += $amount; // Add to the current balance
4 echo '<br>Deposited: $' number_format( $amount, 2);
}
function makeWithdrawal( $amount ) {
// Subtract from the current balance
1 A class called BankAccount is defined
2 This class has only one variable, $balance, initially set to zero The keyword private tells PHP
that this variable can be accessed only from within the class and not from outside Thus,
$myAccount->balance=100000 will fail if that statement is issued from outside the class
3 The only way to alter the balance is through the class methods Method makeDeposit() will add
the $amount to $this->balance Remember, the pseudo-variable $this refers to the object currently being used
4 This line prints the amout that was deposited (The function number_format() is used to
format the dollars with two decimal spaces.) 5–
6
Similarly, the function makeWithdrawal() will deduct $amount from $this-> balance
Trang 197 The getBalance() method returns the value of the current balance Although the user can view
the balance, he or she does not have access to it and cannot change it directly
8 A new object called $myAccount is created
9 The makeDeposit() method is called and adds $100 to the account object, $myaccount
10 The makeWithdrawal() method withdraws $40 from the account object, $ myaccount
11 A call to getBalance() for the object $myAccount will print the balance of $60, the correct
amount The output is shown in Figure 17.6
Figure 17.6 The BankAccount class contains a private variable to hold the balance, accessed only by
public methods to deposit, withdraw, and get the balance Output from Example 17.3
17.2.8 Magic Methods
PHP provides special methods that are invoked automatically based on what the program is doing—creating an object, setting a property value, retrieving a value, or destroying an object A constructor is a magic method that is invoked when you call new to create a new object, a get or set method is invoked when you access the object, and a destructor method
is invoked when your program ends These special methods have names starting with two underscores:
construct(), destruct(), set(), and get() We discuss each of the “magic” methods in the following sections (See the PHP manual for a complete list of magic methods.)
Constructors
A constructor, as the term implies, is a builder or creator When you assign values to properties in a class, PHP will automatically build or construct a new object when new is called by the user of the class When we created a new house, new employee, and new bank account, we did not explicitly call a constructor We let PHP create the object and assign the properties to it If you want to customize the initialization of an object, PHP lets you define a constructor method of your own Once the object has been created with new, PHP will check to see if you have defined a constructor, and if so, it will automatically be called This magic method is called right after new has created the object For example, to set the initial bank account balance to zero for a new bank account, a constructor could be defined to perform this initial task
Trang 20Although functionally the same, PHP 4 and PHP 5 use a different syntax for creating constructor methods PHP 4
constructor methods are named with the same name as the class So, if you have a class named MyClass, the constructor
is a function named MyClass
PHP 5 provides the constructor, a magic method called construct() This method is not normally called directly by the user, but is automatically invoked when the new keyword is used PHP 5 is backward compatible, so if a function named construct() is missing in the class declaration, the old-style constructor will be used if there is one; if neither are declared, then PHP creates the object and assigns it values provided in the class, just as demonstrated in all of the examples thus far
2 function construct(){ // Constructor
print "Constructor initializing a new house.\n";
}
} /* End class definition */
3 $my_house= new House;
4 $your_house=new House;
?>
Explanation
1 A House class is defined
2 The construct method acts as a class constructor and is called when the object is being created (PHP 5)
3 The new keyword is used to create a House object The “magic” function on line 2 is automatically invoked at this time
4 Another House object is created, causing the construct() function to be invoked again See Figure 17.7 (left)
Trang 21Figure 17.7 (left) Using the PHP 5 “magic” constructor method; (right) Using a constructor method named after
the class Output from Examples 17.4 and 17.5
Example 17.5
<?php
# PHP 4
1 class House{
2 function House(){ // Constructor PHP 4
print "Constructor initializing a new house.\n";
}
} /* End class definition */
3 $my_house= new House; // Create object
4 $your_house=new House;
?>
Explanation
1 A House class is defined
2 When the function has the same name as the class, it is a constructor and will be invoked when a new
House object is created
3,
4
Two new House objects are created with the new keyword The constructor on line 2, named after the class, is automatically invoked at this time Prior to PHP 5, this was the only way to create a constructor method
Trang 22}
7 function displayHouse(){
echo "This house is owned by $this->owner ";
echo "It's address is $this->address.\n<br>";
}
}
// Using the class to create objects
8 $myHouse= new House("Joe","13 River Road");
9 $yourHouse = new House("Brad","1 Roundabout Drive");
10 $myHouse->displayHouse();
$yourHouse->displayHouse();
?>
Explanation
1 The House class is declared
2 The $owner property is declared private It cannot be directly accessed from outside the class In this example, declaring this variable private is not really necessary; it is done just to illustrate the scope designator
3 The $address property is publicly available throughout the script
4 PHP’s constructor is defined here A class automatically calls this method for each new object that is created The constructor method accepts arguments of varied types and number
5 This is where the initial values are being set for the new object
6 Each time the contstructor is called, that is, each time a new House object is created, this line is printed, as shown
9 Another House object is created The constructor will automatically be called for this object and assign values to its properties We now have two house objects in the program’s memory, both at different memory addresses and both with their own properties
10 To display the properties of the objects, each object calls displayHouse(), a user-defined function that retrieves and prints the properties of the object that is named on the left side of the -> operator See Figure 17.8
Trang 23Figure 17.8 Calling the constructor in PHP 5 Output from Example 17.6
Destructors
A destructor, as the name implies, is used to destroy an object A destructor method is called right before the object is released Releasing an object means that all references to the object have been unset or the object has gone out of scope The destructor would be used to perform any final actions you want to perform such as deleting old files, releasing
resources, and so on Typically, PHP releases the objects at the end of each script
Being able to use a destructor is a PHP 5 feature PHP 4 does not have destructors at all In PHP 4 you created a function that simulated a destructor or you could use the PHP unset() function to force the removal of an object, but PHP 5 provides a specific destructor function named destruct() This method takes no parameters, and it cannot be called directly It will be called implicitly when you release your object
function construct($owner, $address){
if (! empty($owner) && ! empty($address)){
$this->owner=$owner;
$this->address=$address;
echo "Constructor initializing a new house ";
echo "in the ", get_class($this)," class.\n";
}
}
function displayHouse(){
Trang 24echo "This house is owned by $this->owner ";
echo "Its address is $this->address.\n<br>";
// Using the class to create objects
3 $myHouse= new House("Joe","13 River Road");
$yourHouse = new House("Brad","1 Roundabout Drive");
4 $myHouse->displayHouse();
$yourHouse->displayHouse();
?>
Explanation
1 This is the same House class defined in the previous example
2 The magic destruct() method will be invoked just before the object is about to be destroyed; that is, if
it is unset or the program is finished The value of $this is an object with an ID of #1 for the first house, and
an ID of #2 for the second house The objects are destroyed in the order in which they were constructed (The object ID numbers are created in the order the object is created, but there are some cases where this seems to
be inconsistent See http://devzone.zend.com/node/view/id/168.)
3 The user of the class creates two objects
4 The displayHouse() method prints the properties of both houses All output for this example is shown in Figure 17.9
Figure 17.9 The destructor method Output from Example 17.7
Accessor Methods—Setters and Getters
You do not have access to a real house or bank account until it has been created Likewise you cannot access an object until you have created it, and then you can manipulate it, give it values, extract values, and so on Functions that give you access to an object are called accessor or instance methods, often termed setters and getters A setter is a method used to
Trang 25assign a value to a class variable, and a getter is a method used to retrieve the value of a class variable Simply said, “Put something in, set it; take something out, get it.”
PHP’s Setter and Getter Access Methods
PHP provides two magic methods, set and get, to protect public variables from direct access outside a class These special functions are called automatically whenever the user tries to access an object’s property either by assigning (setting) a value to it or by retrieving (getting) a value The set method takes exactly two arguments, the object’s property variable and the value being assigned to it The get method takes one argument, the property of the object These functions do not work with private variables and each function can only be defined once within the class
Let’s look at an example to see how this works
// Public magic methods
3 function set($property,$value) // setter
// User of the class
7 $Heidi = new Employee();
1 The Employee class is declared
2 The Employee class consists of three public properties, $name, $phone, and $ address
3 This magic method called set takes two parameters: one to represent the incoming class property for the object, in this example called $property; and the second to represent the value that will be assigned to that property When the user of the class makes a statement such as $Heidi->phone="123-456-7890", PHP automatically invokes this set method and assigns properties to the current object, referenced by the pseudo variable, $this