Developing Object-Oriented PHP. PHP-Object Oriented Programming2 Object-Oriented Programming Object-oriented programming (OOP) refers to the creation.

Slides:



Advertisements
Similar presentations
Overview of Data Structures and Algorithms
Advertisements

Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
The Web Warrior Guide to Web Design Technologies
PHP (2) – Functions, Arrays, Databases, and sessions.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Manipulating MySQL Databases with PHP. PHP and mySQL2 Objectives Connect to MySQL from PHP Learn how to handle MySQL errors Execute SQL statements with.
Objectives Connect to MySQL from PHP
ASP.NET Programming with C# and SQL Server First Edition
ASP.NET Programming with C# and SQL Server First Edition
C++ fundamentals.
PHP Programming with MySQL Slide 11-1 CHAPTER 11 Developing Object-Oriented PHP.
Review of C++ Programming Part II Sheng-Fang Huang.
Object Based Programming. Summary Slide  Instantiating An Object  Encapsulation  Inheritance  Polymorphism –Overriding Methods –Overloading vs. Overriding.
Using Data Active Server Pages Objectives In this chapter, you will: Learn about variables and constants Explore application and session variables Learn.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Chapter 8 More Object Concepts
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Objectives In this chapter, you will:
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
Using Visual Basic 6.0 to Create Web-Based Database Applications
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
OOP with PHP Roman Bednarik
Chapter 8 Cookies And Security JavaScript, Third Edition.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
JavaScript, Fourth Edition
Lec_6 Manipulating MySQL Databases with PHP PHP Programming with MySQL.
Chapter 6 PHP Interacts with Mysql Database. Introduction In PHP, there is no consolidated interface. Instead, a set of library functions are provided.
Chapter 6 Object-Oriented Java Script JavaScript, Third Edition.
1 Introduction Modules  Most computer programs solve much larger problem than the examples in last sessions.  The problem is more manageable and easy.
Object-Oriented PHP (Chapter 6).
OOP IN PHP `Object Oriented Programming in any language is the use of objects to represent functional parts of an application and real life entities. For.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
1 Chapter 8 – Classes and Object: A Deeper Look Outline 1 Introduction 2 Implementing a Time Abstract Data Type with a Class 3 Class Scope 4 Controlling.
2010/11 : [1]PHP with MySQLBuilding Web Applications using MySQL and PHP (W1) PHP with MySQL.
Chapter 11: Introduction to Classes. In this chapter you will learn about: – Classes – Basic class functions – Adding class functions – A case study involving.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Chapter 4 Introduction to Classes, Objects, Methods and strings
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Object Oriented Programming
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
CITA 342 Section 1 Object Oriented Programming (OOP)
Chapter 10 Developing Object-Oriented PHP. 2 Objectives In this chapter, you will: Study object-oriented programming concepts Use objects in PHP scripts.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Object-Oriented Programming: Classes and Objects Chapter 1 1.
Programming Logic and Design Seventh Edition
Chapter 3: Using Methods, Classes, and Objects
Objectives Connect to MySQL from PHP Learn how to handle MySQL errors
Object-Oriented Programming: Classes and Objects
Chapter 11 Developing Object-Oriented PHP PHP Programming with MySQL Revised by A. Philipp – Spring 2010 (Rev SP’11)
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Developing Object-Oriented PHP
Tutorial 6 PHP & MySQL Li Xu
Object Oriented Programming in java
Presentation transcript:

Developing Object-Oriented PHP

PHP-Object Oriented Programming2 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

PHP-Object Oriented Programming3 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

PHP-Object Oriented Programming4 Object-Oriented Programming Figure 11-1 Accounting program

PHP-Object Oriented Programming5 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

PHP-Object Oriented Programming6 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

PHP-Object Oriented Programming7 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

PHP-Object Oriented Programming8 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();

PHP-Object Oriented Programming9 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( , 1021, 97.58);

PHP-Object Oriented Programming10 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

PHP-Object Oriented Programming11 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);

PHP-Object Oriented Programming12 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");

PHP-Object Oriented Programming13 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();

PHP-Object Oriented Programming14 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

PHP-Object Oriented Programming15 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();

PHP-Object Oriented Programming16 Handling MySQL Errors With object-oriented style, you cannot terminate script execution with the die() or exit() functions $DBConnect "dongosselin", "rosebud") Or die(" Unable to connect to the database server. ". " Error code ". mysqli_connect_errno(). ": ". mysqli_connect_error()). " ";

PHP-Object Oriented Programming17 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 mysqli("localhost", "dgosselin", "rosebud"); if (mysqli_connect_errno()) die(" Unable to connect to the database server. ". " Error code ". mysqli_connect_errno(). ": ". mysqli_connect_error()). " ";

PHP-Object Oriented Programming18 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 = Or die(" Unable to select the database. ". " Error code ". mysqli_errno($DBConnect). ": ". mysqli_error($DBConnect)). " ";

PHP-Object Oriented Programming19 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

PHP-Object Oriented Programming20 Executing SQL Statements (continued) $TableName = "inventory"; $SQLstring = "SELECT * FROM inventory"; $QueryResult = $DBConnect->query($SQLstring) Or die(" Unable to execute the query. ". " Error code “. $DBConnect->errno. ": “. $DBConnect->error). " "; echo " "; echo " Make Model Price Inventory "; $Row = $QueryResult->fetch_row(); do { echo " {$Row[0]} "; echo " {$Row[1]} "; echo " {$Row[2]} "; echo " {$Row[3]} "; $Row = $QueryResult->fetch_row(); } while ($Row);

PHP-Object Oriented Programming21 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

PHP-Object Oriented Programming22 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

PHP-Object Oriented Programming23 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 }

PHP-Object Oriented Programming24 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();

PHP-Object Oriented Programming25 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. "; Use the instanceof operator to determine whether an object is instantiated from a given class

PHP-Object Oriented Programming26 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

PHP-Object Oriented Programming27 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 ( ) in an external file

PHP-Object Oriented Programming28 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

PHP-Object Oriented Programming29 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

PHP-Object Oriented Programming30 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

PHP-Object Oriented Programming31 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 a data member

PHP-Object Oriented Programming32 Using Access Specifiers 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

PHP-Object Oriented Programming33 Using Access Specifiers 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; }

PHP-Object Oriented Programming34 Serializing Objects Serialization refers to the process of converting an object into a string that you can store for reuse  This enables the sharing of objects within the same session used by multiple scripts  Session variables could be used but you would need to instantiate a new object and reassign the session variable values to the data members each time you call a script – this could be time consuming if the object has dozens of data members Serialization stores both data members and member functions into strings

PHP-Object Oriented Programming35 Serializing Objects To serialize an object, pass an object name to the serialize() function $SavedAccount = serialize($Checking); 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);

PHP-Object Oriented Programming36 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

PHP-Object Oriented Programming37 Working with Member Functions class BankAccount { public $Balance = ; public function withdrawal($Amount) { $this->Balance -= $Amount; } if (class_exists("BankAccount")) $Checking = new BankAccount(); else exit(" The BankAccount class is not available! "); printf(" Your checking account balance is $%.2f. ", $Checking->Balance); $Cash = 200; $Checking->withdrawal(200); printf(" After withdrawing $%.2f, your checking account balance is $%.2f. ", $Cash, $Checking->Balance);

PHP-Object Oriented Programming38 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 = ""; }

PHP-Object Oriented Programming39 Initializing with Constructor Functions 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

PHP-Object Oriented Programming40 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

PHP-Object Oriented Programming41 Cleaning Up with Destructor Functions 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() function __construct() { $DBConnect = new mysqli("localhost", "dongosselin","rosebud", "real_estate") } function __destruct() { $DBConnect->close(); }

PHP-Object Oriented Programming42 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

PHP-Object Oriented Programming43 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(" The BankAccount class is not available! "); $Checking->setBalance(100); echo " Your checking account balance is ". $Checking->getBalance(). " ";

PHP-Object Oriented Programming44 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

PHP-Object Oriented Programming45 Serialization Functions 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()

PHP-Object Oriented Programming46 Serialization Functions Problem: Create a HitCounter class that counts the number of hits to a Web page and stores the results in a mySQL database’ Use a private data member to store the number of hits and include public set and get member functions to access the private counter member variable

PHP-Object Oriented Programming47 HitCounter.php <?php class HitCounter { private $DBConnect; private $DBName = "newdb"; private $TableName = "hits"; private $Hits = 0; function __construct() { $this->DBConnect mysqli("localhost", "root", "mypassword"); if (mysqli_connect_errno()) die(" Unable to connect to the database server. ". " Error code ". mysqli_connect_errno(). ": ". mysqli_connect_error()). " "; } function __destruct() { $this->DBConnect->close(); } public function setDatabase($Database) { $this->DBName = Or die(" Unable to select the database. ". " Error code ". mysqli_errno($this->DBConnect). ": ". mysqli_error($this->DBConnect)). " "; }

PHP-Object Oriented Programming48 HitCounter.php public function setTable($Table) { $this->TableName = $Table; } public function setHits() { $SQLstring = "UPDATE $this->TableName SET hits=$this->Hits WHERE id=1"; $QueryResult $SQLstring) Or die(" Unable to perform the query. ". " Error code ". mysqli_errno($this->DBConnect). ": ". mysqli_error($this->DBConnect)). " "; } public function getHits() { $SQLstring = "SELECT * FROM $this->TableName WHERE id=1"; $QueryResult = $this->DBConnect->query($SQLstring) Or die(" Unable to perform the query. ". " Error code ". mysqli_errno($this->DBConnect). ": ". mysqli_error($DBConnect)). " "; $Row = $QueryResult->fetch_row(); $this->Hits = $Row[1]; $this->Hits = $this->Hits + 1; echo " This page has received ". $this->Hits. " hits. "; }

PHP-Object Oriented Programming49 CountVisits.php <?php require_once("HitCounter.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " Hit Counter Hit Counter <?php $Database = "newdb"; $Table = "hits"; if (class_exists("HitCounter")) { $Counter = new HitCounter(); $Counter->setDatabase($Database); } else exit(" The HitCounter class is not available! "); $Counter->setTable($Table); $Counter->getHits(); $Counter->setHits(); ?>