Chapter 11 Developing Object-Oriented PHP PHP Programming with MySQL Revised by A. Philipp – Spring 2010 (Rev SP’11)

Slides:



Advertisements
Similar presentations
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Advertisements

Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 11 Classes and Object- Oriented Programming.
Object-Oriented PHP (1)
Road Map Introduction to object oriented programming. Classes
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
ASP.NET Programming with C# and SQL Server First Edition
Developing Object-Oriented PHP. PHP-Object Oriented Programming2 Object-Oriented Programming Object-oriented programming (OOP) refers to the creation.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
PHP Programming with MySQL Slide 11-1 CHAPTER 11 Developing Object-Oriented PHP.
Object Based Programming. Summary Slide  Instantiating An Object  Encapsulation  Inheritance  Polymorphism –Overriding Methods –Overloading vs. Overriding.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Chapter 8 More Object Concepts
Writing Classes (Chapter 4)
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Objectives In this chapter, you will:
Module 7: Object-Oriented Programming in Visual Basic .NET
An Object-Oriented Approach to Programming Logic and Design
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
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 Object-Oriented Java Script JavaScript, Third Edition.
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.
Advanced Object- Oriented Programming Programming Right from the Start with Visual Basic.NET 1/e 14.
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.
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.
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
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
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
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
CITA 342 Section 1 Object Oriented Programming (OOP)
Object-Oriented Programming (OOP) What we did was: (Procedural Programming) a logical procedure that takes input data, processes it, and produces output.
Chapter 10 Developing Object-Oriented PHP. 2 Objectives In this chapter, you will: Study object-oriented programming concepts Use objects in PHP scripts.
Object-Oriented Programming: Classes and Objects.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Data Abstraction: The Walls
Programming Logic and Design Seventh Edition
Topics Procedural and Object-Oriented Programming Classes
Advance OOP in PHP.
Chapter 3: Using Methods, Classes, and Objects
PHP Classes and Objects
Object-Oriented Programming: Classes and Objects
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
IFS410: Advanced Analysis and Design
CSCI 3328 Object Oriented Programming in C# Chapter 9: Classes and Objects: A Deeper Look – Exercises UTPA – Fall 2012 This set of slides is revised from.
Developing Object-Oriented PHP
Object Oriented Programming in java
Object-Oriented PHP (1)
Final and Abstract Classes
Classes and Objects Imran Rashid CTO at ManiWeber Technologies.
2.1 Introduction to Object-Oriented Programming
Chapter 7 Objects and Classes
Introduction to Classes and Objects
Presentation transcript:

Chapter 11 Developing Object-Oriented PHP PHP Programming with MySQL Revised by A. Philipp – Spring 2010 (Rev SP’11)

Objectives Study object-oriented programming concepts Use objects in PHP scripts Declare data members in classes Work with class member functions

Object-Oriented Programming Refers to the creation of reusable software objects that can be easily incorporated into multiple programs Object (AKA Components )refers to programming code data treated as an individual unit or component

Object-Oriented Programming Data refers to information contained within variables or other types of storage structures Methods functions associated with an object Properties or Attributes variables that are associated with an object Note: Popular object-oriented programming languages include C++, Java, and Visual Basic

Object-Oriented Programming Figure 11-1 Accounting program

Understanding Encapsulation all code and required data are contained within the object itself hides all internal code and data allow users to see only the methods and properties of the object that you allow them to see reduces the complexity of the code prevents other programmers from accidentally introducing a bug into a program, or stealing code Interface methods and properties that are required for a source program to communicate with an object

Classes Classes Instance Instantiating Inheritance Organization for code, methods, attributes, and other information that make up an object Instance object that has been created from an existing class Instantiating creating an object from an existing class Inheritance objects takes on the characteristics of the class on which it is based

Using Objects Declare an Object Syntax for Instantiation Identifiers new operator with a class constructor Syntax for Instantiation $ObjectName = new ClassName(); Identifiers Must begin with a dollar sign Can include numbers or an underscore Cannot include spaces Are case sensitive $Checking = new BankAccount();

Using Objects (continued) Member Selection Notation -> Access the methods and properties contained in the object

Using Objects (Continued) Properties $Checking -> Balance Methods include a set of parentheses at the end of the method name methods can also accept arguments $Checking -> getBalance(); $CheckNumber = 1022; $Checking -> getCheckAmount($ChkNum);

Database Connections as Objects MySQL database connections as objects instantiating an object from the mysqli class Traditional $DBConnect = mysqli_connect("localhost",“root",""); mysqli_select_db($DBConnect,”RealEstate"); …… mysqli_close($DBConnect); Object-Oriented $DBConnectObj = new mysqli("localhost", "root", "", "Real Estate"); …… $DBConnectObj->close(); Note: Can select another database $DBConnectObj->select_db(“New Listings");

Handling MySQL Errors - OOP mysqli constructor always creates a new object even if connection fails must test for errors Must check the values assigned to the mysqli_connect_errno()or mysqli_connect_error() Use error codes/statements with a selection structure $DBConnectObj = @new mysqli("localhost", "root", "", "Real Estate"); if (mysqli_connect_errno()) { echo ("<p>Error Code“. mysqli_connect_errno().":“. mysqli_connect_error())."</p>"; }

Executing SQL Statements MySQL DataBase Query Traditional $QueryResult = mysqli_query($DBConnect, $SQLString) … $Row = mysqli_fetch_row($QueryResult) $Row = mysqli_fetch_assoc($QueryResult); Object-Oriented $QueryResultObj=$DBConnectObj->query($SQLstring) …. $Row = $QueryResultObj->fetch_row(); $Row = $QueryResultObj->fetch_assoc();

Executing SQL Statements Use query()method of mysqli class Must check for NULL not FALSE FALSE will result in infinite loop $QueryResultObj=$DBConnectObj->query($SQLstring) … while (($Row = $QueryResultObj->fetch_row())!=NULL); { //do something }

Defining Custom PHP Classes Data Structure system for organizing data Class Members functions and variables defined in a class Data Members or Member Variables Class variables Member Functions or Function Members Class functions

Creating a Class Definition Keyword used to write a class definition Class definition The data members and member functions that make up the class Syntax for defining a class class ClassName { data/function member definitions }

Creating a Class Definition (Continued) ClassName Name of the new class Usually begin with an uppercase letter to distinguish them from other identifiers Within the class’s curly braces, declare the data type / field names for all information stored in the structure class BankAccount { data member definitions member function definitions } $Checking = new BankAccount();

Creating a Class Definition (Continued) Get_class() returns name of that instantiated it $Checking = new BankAccount(); echo “$Checking object is instantiated from the ”. get_class($Checking). ” class."; instanceof determines if an object is instantiated from a given class if ($Checking instanceof BankAccount){ Echo “The \$Checking object is from BankAccount class”;

Storing Classes in External Files Class files should begin with class_ class_BankAcccount.php Similar to inc_SomeIncludeFile.php Functions for external files in PHP scripts: include() require() include_once() require_once() Pass to each function the name and path of the external file

Collecting Garbage 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 when an object of variable is no longer needed Exception: open database connections

Information Hiding Any class members that other programmers/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

Using Access Specifiers controls a client’s access to individual data members and member functions Public items can be accessed everywhere Private limits visibility only to the class that defines the item Protected limits access to inherited and parent classes (and to the class that defines the item)

Using Access Specifiers (Continued) Include an access specifier at the beginning of a data member declaration statement Always assign an initial value to a data member when you first declare it class BankAccount { public $Balance = 0; }

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 class BankAccount { private $Balance = 958.20; public function withdrawal($Amount) { $this->Balance -= $Amount; } Note: $this – psuedo variable that is reference to the calling object

Constructors and Destructors function is called when a class object is first instantiated Destructor function is called when the object is destroyed cleans up any resources allocated to an object after the object is destroyed

Constructor Functions Special function - called automatically when an object from a class is instantiated The __construct() function takes precedence over a function with the same name as the class - BankAccount in this example Commonly used to handle database connections class BankAccount { private $AccountNumber; private $CustomerName; private $Balance; function __construct() { //could be BankAccount() $this->AccountNumber = 0; $this->Balance = 0; $this->CustomerName = ""; }

Destructor Functions (Continued) Calling Destructors When a script ends Delete an object with unset() Adding a destructor function to a class, create a function named __destruct() function __construct() { $DBConnectObj = new mysqli("localhost", "root", "", "RealEstate"); } function __destruct() { $DBConnectObj->close();

Writing Accessor Functions Public member functions Client can call to retrieve or modify the value of a data member Begin with the words “set” or “get” Set functions modify data member values Get functions retrieve data member values

Writing Accessor Functions (Continued) class BankAccount { private $Balance = 0; public function setBalance($NewValue) { $this->Balance = $NewValue; } public function getBalance() { return $this->Balance; if (class_exists("BankAccount")) $Checking = new BankAccount(); else exit("<p>The BankAccount is not available!</p>"); $Checking->setBalance(100); echo "<p>Checking balance: ". $Checking->getBalance() . "</p>";

Serialization Serialization Convert an object into a string Store for reuse Stores data members and member functions into strings Store the data in large arrays To serialize/unserialize an object, pass an object name $Saved = serialize($Checking); $Checking = unserialize($Saved); Assign a serialized object to a session variable session_start(); $_SESSION('Saved')=serialize($Checking);

Serialization: sleep(), wakeup() serialize() PHP looks in the object’s class for __sleep() specifies which data members of the class to serialize, otherwise serializes all members function __sleep() { $SerialVars = array('Balance'); return $SerialVars;} unserialize() PHP looks in the object’s class for __wakeup() used to restore DB connections lost during serialization function __wakeup(){ } FYI: According to PHP.net any function names that begin with __ (Double _ _ not single _ ) are referenced as magical.

Object-Oriented Review The term “object-oriented programming (OOP)” refers to the creation of reusable software objects that can be easily incorporated into multiple programs. The term “object” specifically refers to programming code and data that can be treated as an individual unit or component (object) The term “data” refers to information contained within variables or other types of storage structures The functions associated with an object are called methods, and the variables associated with an object are called properties or attributes Objects are encapsulated, which means that all code and required data are contained within the object itself An interface represents elements required for a source program to communicate with an object In object-oriented programming, the code, methods, attributes, and other information that make up an object are organized into classes An instance is an object that has been created from an existing class. When you create an object from an existing class, you are “instantiating the object” A particular instance of an object inherits its methods and properties from a class—that is, it takes on the characteristics of the class on which it is based A constructor is a special function with the same name as its class; it is called automatically when an object from the class is instantiated The term “data structure” refers to a system for organizing data The functions and variables defined in a class are called class members. Class variables are referred to as data members or member variables, whereas class functions are referred to as member functions or function members A class definition contains the data members and member functions that make up the class PHP provides the following functions that allow you to use external files in your PHP scripts: include(), require(), include_once(), and require_once()

Object-Oriented Review The principle of information hiding states that class members should be hidden when other programmers do not need to access or know about them Access specifiers control a client’s access to individual data members and member functions Serialization refers to the process of converting an object into a string that you can store for reuse A constructor function is a special function that is called automatically when an object from a class is instantiated When you serialize an object with the serialize() function, PHP looks in the object’s class for a special function named __sleep(), which you can use to perform many of the same tasks as a destructor function When the unserialize() function executes, PHP looks in the object’s class for a special function named __wakeup(), which you can use to perform many of the same tasks as a constructor function A destructor function cleans up any resources allocated to an object after the object is destroyed Accessor functions are public member functions that a client can call to retrieve the value of a data member Mutator functions are public member functions that a client can call to modify the value of a data member