PHP and MySQL by Example- P15

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

0
38
lượt xem
9
download

PHP and MySQL by Example- P15

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Tham khảo tài liệu 'php and mysql by example- p15', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả

Chủ đề:
Lưu

Nội dung Text: PHP and MySQL by Example- P15

  1. 4 < br /> 5 < br /> ##### login.html ##### ##### end ##### Explanation 1 This  is  a  link  to  the  protected  page  (page  3)  where  special  content  can  be  read  only  if   the  visitor  has  typed  in  a  valid  username  and  password. 2 After  the  form  has  been  submitted,  the  PHP  script  (page  2),  auth.php,  will  be   executed.  This  page  will  determine  whether  or  not  the  visitor  is  authorized  to  log  in. 3 The  visitor  is  asked  to  type  in  the  username  here.  See  Figures  16.36  and  16.37. 4 This  is  where  the  user  types  in  the  password. 5 To  submit  information  that  is  not  entered  by  the  visitor,  a  hidden  field  is  used  and   assigned  the  value  "login".   Figure 16.36. Page 1: The login.html file. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  2. Figure 16.37. Page 1: The visitor fills out the form. Example 16.26. Code  View:   (Page 2) ##### begin ##### ##### auth.php #####
  3. 6 session_write_close(); 7 header("Location: protected.php"); } // User is logging out 8 if (isset($_GET["logout"])){ 9 session_destroy(); 10 header("Location: login.html"); } ?> ##### auth.php ##### ##### end #### Explanation 1 The  session  for  this  page  starts  here  for  auth.php  (page  2). 2 If  the  user  has  filled  out  the  login  form  in  login.html  (page  1),  then  the   $_POST["login"]  variable  will  be  set,  and  the  statements  in  the  if  block  will   be  executed. 3 If  the  username  is  set  and  has  a  value  "phpbee",  and  the  password  is  set  and   also  has  the  value  "phpbee",  the  statement  in  line  4  is  executed. 4 The  session  variable  is  set  to  1.  The  value  of  1  will  be  used  later  to  determine   that  the  user  is  logged  in. 5 If  either  a  valid  username  or  password  were  not  entered,  the  session  variable   is  set  to  0.  A  value  of  0  will  be  used  to  determine  that  the  user  is  not  logged   in. 6 The  session_write_close()  function  stores  the  session  data  now  and  closes   the  session. 7 The  user  is  directed  to  protected.php  (page  3).  This  is  the  page  that  is  not   accessible  to  anyone  who  is  not  logged  in. 8 If  the  user  entered  the  protected  page  and  clicked  the  link  to  log  out,  the   variable  $_GET["logout"]  will  be  set,  and  the  statements  in  the  if  block  will   be  executed. 9 The  session  and  all  its  data  are  destroyed. 10 The  user  is  redirected  back  to  the  login  page.  Because  the  session  was   destroyed,  he  or  she  is  no  longer  authenticated  to  go  to  the  protected  page. Example 16.27. Code  View:   (Page 3) Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  4. ##### begin ##### ##### protected.php ##### Protected page 3 Protected content Hello. Since you are logged in, you can view protected content 4 You can also log out You are not logged in Hello. Since you are not logged in, you cannot view protected content 5 But you can log in ##### protected.php ##### ##### end ##### Explanation 1 The  session  starts  for  page  3.  See  Figure  16.38. 2 If,  on  page  2,  the  session  variables  were  set  and  $SESSION["Authenticated"]  was  set  to   1,  the  visitor  is  logged  in  and  will  be  able  to  read  whatever  is  on  line  3. 3 This  is  where  the  content  would  be  added  for  this  page,  the  content  only  viewable  if  the   user  successfully  logged  in. 4 This  link  will  send  the  user  back  to  page  2,  auth.php.  The  word  logout  appended  to  the   question  mark,  will  be  passed  via  the  GET  method  and  assigned  to  the  $_GET[]  array. 5 This  link  returns  the  visitor  back  to  the  login  page,  page  1.   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  5. Figure 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.) Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  6. 16.5.1. What You Should Know Now that you have finished this chapter you should be able to answer the following questions: 1. What  is  meant  by  stateless? 2. What  are  cookies  used  for  and  where  do  they  reside? 3. What  is  the  life  span  of  a  cookie? 4. How  are  cookies  sent  from  the  server  to  the  browser? 5. How  does  PHP  store  cookies? 6. What  is  serialization? 7. What  is  the  advantage  of  using  PHP  sessions? 8. What  is  meant  by  a  cookie-­‐based  session? 9. What  is  a  session  ID  number  and  where  is  it  stored? 10. What  are  the  PHP  buffering  functions? 11. How  are  sessions  registered? 12. How  are  sessions  deleted? 13. What  is  the  purpose  of  the  PHP  session_write_close()  function? 14. What  is  garbage  collection? 15. What  are  the  disadvantages  of  using  cookies?  What  are  the  disadvantages  of   using  sessions? 16.5.2. What’s Next? The next and last chapter introduces object-oriented programming with PHP. You will learn how to create classes to encapsulate data and functions. You will create instances of a class, called objects, and assign properties to describe the object. You will design methods, special functions, to manipulate the object and learn how to keep the object’s data protected from outside access. You will see how one class inherits from another. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  7. Chapter 16 Lab 1. Create  a  login  page  that  asks  the  user  for  a  username  and  password.  Trim  the   username  and  password  to  remove  any  unwanted  whitespace.  The  action   attribute  of  the  from  will  redirect  you  to  a  new  page,  called  verify.php. 2. The  verify.php  page  will  start  a  session  and  check  that  the  username  and   password  fields  are  not  empty  and  also  that  they  are  correct.  If  not,  the  user  will  be   informed,  and  redirected  back  to  the  login  page.  If  correct,  the  user  will  be  directed   to  your  home  page  (you  may  want  to  use  the  database  form  from  the  last  exercise). 3. When  the  user  is  ready  to  log  out,  end  the  session. 4. Create  a  drop-­‐down  menu  that  allows  the  user  to  select  from  a  list  of  vacation   spots.  Save  his  choices  in  a  cookie. 5. Link  to  another  page  that  will  print  images  of  the  vacation  spots  that  the  user   selected. 6. When  the  user  returns  to  the  menu,  he  or  she  will  see  the  list  selected  the  last  time   he  or  she  was  on  this  page.   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  8. Chapter 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 real- world objects. Some people are apprehensive at the thought of tackling this kind of programming, and are perfectly happy to stick with 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. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  9. Figure 17.1. A House class. 17.2. Working with Classes 17.2.1. Defining the Class To  create  a  class  you  use  the  class  keyword  followed  by  the  name  of  the  class.  The  class   definition,  like  a  function  definition,  is  enclosed  in  a  set  of  curly  braces.  The  name  of  a  class   follows  the  same  naming  conventions  as  normal  variables  (minus  the  dollar  sign)  and  the  class   name,  by  convention,  starts  with  a  capital  letter.  For  example:     The  class  House  might  have  variables  (called  attributes)  such  as  $owner, $address,  $color,  or   $number_of_rooms,  as  well  as  functions  (called  methods),  such  a  showHouse(),  cleanHouse(),  or   paintHouse(),  for  example.   Once  the  class  is  defined,  it  is  used  to  create  specific  objects.  Just  as  when  you  design  a  blueprint   for  a  house,  the  real  house  does  not  yet  exist.  You  must  build  it  from  the  blueprint.  The  class  is   analogous  to  the  blueprint  and  the  object  to  the  actual  house.  We  could  build  many  houses  from   the  same  blueprint  and  we  can  build  many  objects  from  a  class.  Just  as  a  house  is  located  at  an   address,  each  object  has  its  own  memory  address.  PHP  provides  the  address  and  cleans  up  the   memory  when  the  object  is  no  longer  needed,  when  the  program  ends.   Once  we  have  the  basic  stuff  of  which  houses  are  made,  we  can  extend  the  blueprint  to  add  new   features  to  the  house,  such  as  a  new  family  room  or  a  fireplace.  Classes  can  also  be  extended  to   create  more  refined  objects.  Extending  a  class  is  called  inheritance.  Inheritance  allows  the   programmer  to  create  a  new  class  without  writing  a  brand  new  one.  He  or  she  can  reuse  an   existing  class  and  add  some  new  features  and  functionality.  Inheritance  is  one  of  the  benefits  of   OOP  that  we  discuss  later  in  this  chapter.   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  10. 17.2.2. Instantiating the Class Once  the  class  is  declared,  the  object  needs  to  be  created.  In  the  real  world  you  would  build  a   new  house;  in  the  object-­‐oriented  world,  you  would  instantiate  a  new  House  class  or  create  a  new   instance  of  the  House  class.  To  make  a  new  object,  we  use  the  reserved  keyword  new.  To   reference  the  object,  we  use  the  special  variable  called  $this.  Each  instance  of  a  class  has  the   same  property,  but  different  copies,  so  that  the  values  can  be  different;  for  example,  if  you  have   two  house  objects  of  the  same  class,  and  each  house  object  has  a  property  called  $owner,  the   values  assigned  to  $owner  can  differ  from  house  object  to  house  object,  just  like  in  the  real  world.   What’s “new”? The  difference  between  an  object  and  a  class  is  that  a  class  is  conceptual  and  an  object  is  real.   The  object  is  the  actual  variable  that  you  manipulate.  You  can  assign  and  retrieve  its  values,  pass   it  to  functions,  delete  it,  copy  it,  and  so  forth.  It  holds  a  specific  set  of  data.  The  new  keyword  is   used  to  create  a  PHP  object  that  is  an  “instance”  of  a  class.   $myhouse = new House;   The  new  keyword  causes  PHP  to  look  for  a  class  named  House,  create  a  new  copy,  and  assign  it  to   the  variable  $myhouse.  A  new  House  object  has  been  instantiated,  which  is  like  saying  “We  just   built  a  new  house  and  called  it  $myhouse,”  and  to  make  another  object  from  the  House  blueprint,   you  could  say:   $yourhouse = new House;   Now  we  have  two  instances  of  the  House  class,  two  house  objects,  $myhouse  and  $yourhouse  (see   Figure  17.2).   Figure 17.2. Instantiating the House class.       The Properties and Methods Properties  (variables)  and  methods  (functions)  together  are  called  class  “members.”  The   properties  of  a  class  are  defined  as  variables.  Before  PHP  5,  the  keyword  var  was  used  to  define  a   public  property  of  the  class;  that  is,  a  property  variable  that  is  visible  throughout  the  current   PHP  script.  The  var  keyword  has  been  deprecated  as  of  PHP  5;  you  now  declare  public   properties  with  the  public  keyword.  Methods  (class  functions)  default  to  public  so  you  do  not   need  to  specify  them  as  public:   (PHP  4)   var $owner = "John Doe:; var $address; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  11.   (PHP  5)   $owner = "John Doe"; // Default is public public $address;   You  can  assign  initial  values  to  the  variables,  but  they  must  be  string  or  numeric  constants,  not   expressions  like  5*6.  New  properties  can  be  added  at  any  time.   A  method  is  a  function  defined  within  the  class.  It  describes  the  behaviors  of  the  class.  It  looks   like  any  other  function  in  structure:   function cleanHouse(){ echo $this->owner; echo $this->address; }   The  one  major  difference  between  methods  and  ordinary  PHP  functions  is  the  $this  keyword   used  to  reference  the  current  object,  and  in  the  way  the  methods  are  invoked.   What’s $this? When  a  class  is  defined,  the  object  is  created  later,  making  it  impossible  for  the  class  writer  to   know  what  the  user  of  the  class  will  name  his  or  her  objects.  To  reference  an  object,  PHP   provides  a  pseudo-­‐variable,  called  $this,  which  references  the  current  object.  If  the  class  built  the   two  house  objects  as  shown  in  the  last  section,  then  it  would  be  able  to  keep  track  of  which   house  was  being  used,  because  $this  always  references  the  current  object.  For  example,  if  myhouse   is  the  current  object,  then  all  the  properties  and  methods  of  the  class  apply  to  myhouse.  If  the   class  has  defined  a  cleanHouse()  method  for  each  house  object,  $this  references  the  house  object   currently  being  used  and  $this>cleanHouse()  applies  to  that  object.  In  real-­‐world  terms,  when  I  am   in  my  house,  I  am  not  going  to  be  cleaning  your  house.  Notice  that  each  property  is  preceded   with  the  $this  variable  and  an  arrow  operator.  If  you  have  many  house  objects,  then  $this  will   keep  track  of  which  house  you  are  currently  using,  both  its  properties  and  methods.   function cleanHouse(){ echo $this->owner; echo $this->address; }   As  we  go  further  on,  you  will  see  how  useful  $this  is.   The -> Operator After  a  class  has  been  defined,  it  can  be  instantiated;  that  is,  we  create  objects  of  that  class.  As   you  will  see  next,  to  assign  properties  and  call  methods,  an  arrow  operator  is  used  to  get  or  set   the  value  of  the  property;  for  example,  if  an  object  called  $myhouse  is  created,  to  assign  a  value  for   the  address  property,  the  statement  might  look  like  this:   $myhouse->address="14 Main St.";   To  call  the  method  showHouse(),  it  might  look  like  this:   $myhouse->showHouse();   The  name  of  the  object  precedes  the  arrow  and  the  property  or  method  so  that  PHP  knows  to   which  object  the  property  and  method  apply.   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  12. Figure 17.3. A House class and creating a house object and accessing it.       The gettype() and get_class() Functions PHP  provides  a  number  of  built-­‐in  functions  that  return  information  about  classes  and  objects.   Table  17.1  gives  you  a  complete  list.  Two  functions  that  will  be  helpful  as  you  start  learning   about  objects  are  the  gettype()  and  the  get_class()  functions.  As  you  might  remember  (see  Chapter   4,  “The  Building  Blocks”)  from  when  we  discussed  data  types,  the  gettype()  function  takes  a   variable  as  its  argument  and  returns  its  data  type,  such  as  string,  boolean,  array,  and  so  on.  It   will  return  “object”  if  the  argument  represents  an  object  that  was  created  using  the  new   keyword.  The  get_class()  function  will  tell  you  the  name  of  the  class  from  which  the  object  was   created.     Table 17.1. PHP Built-In Class Functions Function What It Does Example get_class() Returns the name of the class string get_class([object obj]) of an object. get_class_vars() Returns an associative array arrayget_class_vars(string of public properties. class_name) get_declared_classes() Returns an array of classes array get_declared_classes(void) defined in the current script. get_object_vars() Returns an array of array get_object_vars(object obj) properties for an object. get_parent_class() Returns the name of the string get_parent_class([mixed obj]) parent class for the class or object. gettype() Returns the data type of a string gettype(mixed var) variable; if an object is given, returns “object.” Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  13. Table 17.1. PHP Built-In Class Functions Function What It Does Example instanceof (PHP 5) A type operator that has instanceof classname replaced is_a(). interface_exists() Returns true if an interface bool interface_exists(string has been defined. interface_name [, bool autoload]) is_a() Returns true if the object is bool is_a(object object, string of this class or this class is class_name) its parent. is_subclass_of() Returns true if object has this bool is_subclass_of(mixed object, class as one of its parents. string class_name) method_exists() Returns true if this method bool method_exists(object object, exists. string method_name) property_exists() Returns true if property bool property_exists(mixed class, exists in the class and is string property) accessible. Example 17.1.
  14. 6 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. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  15. Figure 17.5. The Employee class and how it is used. Example 17.2. Code View:
  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"; 12 $Brad->address = "4321 Sunset Blvd "; 13 $Brad->phone = "987-654-3210"; 14 $Heidi->printPersonInfo(); // Access the object with the method 15 $Brad->printPersonInfo(); ?> Explanation 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– Values are assigned to the properties of object $Brad. 13 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 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  17. [address] => 1234 Somewhere Blvd [phone] => 123-456-7890 ) Employee Object ( [name] => Brad Bit [address] => 4321 Sunset Blvd [phone] => 987-654-3210 ) 17.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. class Employee{ private $name; private $phone; private $address; } The methods used to manipulate this data would be publicly available. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  18. Protected 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. Example 17.3. Code View: Explanation 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– Similarly, the function makeWithdrawal() will deduct $amount from $this-> balance. 6 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  19. 7 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. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  20. Although 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. Format PHP 4 Format: void class_name([mixed args[, ...]) Example: function MyClass(){ $this->balance = 0; } PHP 5 Format: void __construct ( [mixed args [, ...]] ) Example: function __construct() { $this->balance = 0; } Example 17.4. 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). Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Đồng bộ tài khoản