Wednesday, November 14, 2007
By far the largest and most heralded change in PHP5 is the complete revamping of the object model and the greatly improved support for standard object-oriented (OO) methodologies and techniques. This book is not focused on OO programming techniques, nor is it about design patterns. There are a number of excellent texts on both subjects (a list of suggested reading appears at the end of this chapter). Instead, this chapter is an overview of the OO features in PHP5 and of some common design patterns.
I have a rather agnostic view toward OO programming in PHP. For many problems, using OO methods is like using a hammer to kill a fly. The level of abstraction that they offer is unnecessary to handle simple tasks. The more complex the system, though, the more OO methods become a viable candidate for a solution. I have worked on some large architectures that really benefited from the modular design encouraged by OO techniques.
This chapter provides an overview of the advanced OO features now available in PHP. Some of the examples developed here will be used throughout the rest of this book and will hopefully serve as a demonstration that certain problems really benefit from the OO approach.
OO programming represents a paradigm shift from procedural programming, which is the traditional technique for PHP programmers. In procedural programming, you have data (stored in variables) that you pass to functions, which perform operations on the data and may modify it or create new data. A procedural program is traditionally a list of instructions that are followed in order, using control flow statements, functions, and so on. The following is an example of procedural code:
Code View: Scroll / Show All
function hello($name)
{
return "Hello $name!\n";
}
function goodbye($name)
{
return "Goodbye $name!\n";
}
function age($birthday) {
$ts = strtotime($birthday);
if($ts === -1) {
return "Unknown";
}
else {
$diff = time() - $ts;
return floor($diff/(24*60*60*365));
}
}
$name = "george";
$bday = "10 Oct 1973";
print hello($name);
print "You are ".age($bday)." years old.\n";
print goodbye($name);
? >
Introduction to OO Programming
It is important to note that in procedural programming, the functions and the data are separated from one another. In OO programming, data and the functions to manipulate the data are tied together in objects. Objects contain both data (called attributes or properties) and functions to manipulate that data (called methods).
An object is defined by the class of which it is an instance. A class defines the attributes that an object has, as well as the methods it may employ. You create an object by instantiating a class. Instantiation creates a new object, initializes all its attributes, and calls its constructor, which is a function that performs any setup operations. A class constructor in PHP5 should be named __construct() so that the engine knows how to identify it. The following example creates a simple class named User, instantiates it, and calls its two methods:
class User {
public $name;
public $birthday;
public function __construct($name, $birthday)
{
$this->name = $name;
$this->birthday = $birthday;
}
public function hello()
{
return "Hello $this->name!\n";
}
public function goodbye()
{
return "Goodbye $this->name!\n";
}
public function age() {
$ts = strtotime($this->birthday);
if($ts === -1) {
return "Unknown";
}
else {
$diff = time() - $ts;
return floor($diff/(24*60*60*365)) ;
}
}
}
$user = new User('george', '10 Oct 1973');
print $user->hello();
print "You are ".$user->age()." years old.\n";
print $user->goodbye();
?>
Running this causes the following to appear:
Hello george!
You are 29 years old.
Goodbye george!
The constructor in this example is extremely basic; it only initializes two attributes, name and birthday. The methods are also simple. Notice that $this is automatically created inside the class methods, and it represents the User object. To access a property or method, you use the -> notation.
On the surface, an object doesn't seem too different from an associative array and a collection of functions that act on it. There are some important additional properties, though, as described in the following sections:
*
Inheritance— Inheritance is the ability to derive new classes from existing ones and inherit or override their attributes and methods.
*
Encapsulation— Encapsulation is the ability to hide data from users of the class.
*
Special Methods— As shown earlier in this section, classes allow for constructors that can perform setup work (such as initializing attributes) whenever a new object is created. They have other event callbacks that are triggered on other common events as well: on copy, on destruction, and so on.
*
Polymorphism— When two classes implement the same external methods, they should be able to be used interchangeably in functions. Because fully understanding polymorphism requires a larger knowledge base than you currently have, we'll put off discussion of it until later in this chapter, in the section "Polymorphism."
Inheritance
You use inheritance when you want to create a new class that has properties or behaviors similar to those of an existing class. To provide inheritance, PHP supports the ability for a class to extend an existing class. When you extend a class, the new class inherits all the properties and methods of the parent (with a couple exceptions, as described later in this chapter). You can both add new methods and properties and override the exiting ones. An inheritance relationship is defined with the word extends. Let's extend User to make a new class representing users with administrative privileges. We will augment the class by selecting the user's password from an NDBM file and providing a comparison function to compare the user's password with the password the user supplies:
class AdminUser extends User{
public $password;
public function _ _construct($name, $birthday)
{
parent::_ _construct($name, $birthday);
$db = dba_popen("/data/etc/auth.pw", "r", "ndbm");
$this->password = dba_fetch($db, $name);
dba_close($db);
}
public function authenticate($suppliedPassword)
{
if($this->password === $suppliedPassword) {
return true;
}
else {
return false;
}
}
}
Although it is quite short, AdminUser automatically inherits all the methods from User, so you can call hello(), goodbye(), and age(). Notice that you must manually call the constructor of the parent class as parent::_ _constructor(); PHP5 does not automatically call parent constructors. parent is as keyword that resolves to a class's parent class.
Encapsulation
Users coming from a procedural language or PHP4 might wonder what all the public stuff floating around is. Version 5 of PHP provides data-hiding capabilities with public, protected, and private data attributes and methods. These are commonly referred to as PPP (for public, protected, private) and carry the standard semantics:
*
Public— A public variable or method can be accessed directly by any user of the class.
*
Protected— A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class.
*
Private— A private variable or method can only be accessed internally from the class in which it is defined. This means that a private variable or method cannot be called from a child that extends the class.
Encapsulation allows you to define a public interface that regulates the ways in which users can interact with a class. You can refactor, or alter, methods that aren't public, without worrying about breaking code that depends on the class. You can refactor private methods with impunity. The refactoring of protected methods requires more care, to avoid breaking the classes' subclasses.
Encapsulation is not necessary in PHP (if it is omitted, methods and properties are assumed to be public), but it should be used when possible. Even in a single-programmer environment, and especially in team environments, the temptation to avoid the public interface of an object and take a shortcut by using supposedly internal methods is very high. This quickly leads to unmaintainable code, though, because instead of a simple public interface having to be consistent, all the methods in a class are unable to be refactored for fear of causing a bug in a class that uses that method. Using PPP binds you to this agreement and ensures that only public methods are used by external code, regardless of the temptation to shortcut.
Static (or Class) Attributes and Methods
In addition, methods and properties in PHP can also be declared static. A static method is bound to a class, rather than an instance of the class (a.k.a., an object). Static methods are called using the syntax ClassName::method(). Inside static methods, $this is not available.
A static property is a class variable that is associated with the class, rather than with an instance of the class. This means that when it is changed, its change is reflected in all instances of the class. Static properties are declared with the static keyword and are accessed via the syntax ClassName::$property. The following example illustrates how static properties work:
class TestClass {
public static $counter;
}
$counter = TestClass::$counter;
If you need to access a static property inside a class, you can also use the magic keywords self and parent, which resolve to the current class and the parent of the current class, respectively. Using self and parent allows you to avoid having to explicitly reference the class by name. Here is a simple example that uses a static property to assign a unique integer ID to every instance of the class:
class TestClass {
public static $counter = 0;
public $id;
public function _ _construct()
{
$this->id = self::$counter++;
}
}
Special Methods
Classes in PHP reserve certain method names as special callbacks to handle certain events. You have already seen _ _construct(), which is automatically called when an object is instantiated. Five other special callbacks are used by classes: _ _get(), _ _set(), and _ _call() influence the way that class properties and methods are called, and they are covered later in this chapter. The other two are _ _destruct() and _ _clone().
_ _destruct() is the callback for object destruction. Destructors are useful for closing resources (such as file handles or database connections) that a class creates. In PHP, variables are reference counted. When a variable's reference count drops to 0, the variable is removed from the system by the garbage collector. If this variable is an object, its _ _destruct() method is called.
The following small wrapper of the PHP file utilities showcases destructors:
class IO {
public $fh = false;
public function _ _construct($filename, $flags)
{
$this->fh = fopen($filename, $flags);
}
public function _ _destruct()
{
if($this->fh) {
fclose($this->fh);
}
}
public function read($length)
{
if($this->fh) {
return fread($this->fh, $length);
}
}
/* ... */
}
In most cases, creating a destructor is not necessary because PHP cleans up resources at the end of a request. For long-running scripts or scripts that open a large number of files, aggressive resource cleanup is important.
In PHP4, objects are all passed by value. This meant that if you performed the following in PHP4:
$obj = new TestClass;
$copy = $obj;
you would actually create three copies of the class: one in the constructor, one during the assignment of the return value from the constructor to $copy, and one when you assign $obj to $copy. These semantics are completely different from the semantics in most other OO languages, so they have been abandoned in PHP5.
In PHP5, when you create an object, you are returned a handle to that object, which is similar in concept to a reference in C++. When you execute the preceding code under PHP5, you only create a single instance of the object; no copies are made.
To actually copy an object in PHP5, you need to use the built-in _ _clone() method. In the preceding example, to make $copy an actual copy of $obj (and not just another reference to a single object), you need to do this:
$obj = new TestClass;
$copy = $obj->_ _clone();
For some classes, the built-in deep-copy _ _clone() method may not be adequate for your needs, so PHP allows you to override it. Inside the _ _clone() method, you have $this, which is the new object with all the original object's properties already copied. For example, in the TestClass class defined previously in this chapter, if you use the default _ _clone() method, you will copy its id property. Instead, you should rewrite the class as follows:
class TestClass {
public static $counter = 0;
public $id;
public $other;
public function _ _construct()
{
$this->id = self::$counter++;
}
public function _ _clone()
{
$this->id = self::$counter++;
}
}
Monday, October 22, 2007
Object Oriented Programming in PHP
Beginning Object Oriented Programming in PHP
In this tutorial you will explore OOP in a way that'll start you on the fast track to polished OOP skills.
Object-Oriented Programming (OOP) tutorials are generally bogged down with programming theory and large metaphysical words such as encapsulation, inheritance and abstraction. They attempt to explain things by comparing code samples to microwaves or automobiles, which only serves to confuse the reader more.
But even when all the hype and mystique that surrounds OOP has been stripped away, you'll find it is indeed a good thing. I won't list reasons why... I don't want this to be another cookie-cutter tutorial that only serves to confuse you. Instead, we'll explore OOP in a way that'll start you on the fast track to polished OOP skills. As you grow in confidence with your skills and begin to use them more in your projects, you'll most likely form your own list of benefits.
Beginning Object Oriented Programming in PHP - Objects - The Magic Box
Imagine a box. It can be any type of box you want: a small jewelry box, a large crate, wooden, plastic, tall and thin, Short and wide...
Next, imagine yourself placing something inside the box: a rock, a million dollars, your younger sibling...
Wouldn't it be convenient if we could walk up to the box and just ask it to tell us what's inside instead of opening it ourselves? Actually, we can!
$mybox = new Box("Jack");
echo $mybox->get_whats_inside();
?>
Here the variable $mybox represents our self-aware box (also known as an object) which will be built by new--the world's smallest engineering and construction team. We also want to place Jack inside the box when it is built. When we want to ask the box it's contents, we'll apply a special get_whats_inside function to $mybox.
The code won't run quite yet, though. We haven't supplied new with the directions for him and his team to construct our box and PHP doesn't know what the function get_whats_inside is supposed to do.
Beginning Object Oriented Programming in PHP - Classes
A class is technically defined as a representation of an abstract data type. In laymen's terms a class is a blueprint from which new will construct our box. It's made up of variables and functions that allow our box to be self-aware. With the blueprint, new can build our box exactly to our specifications.
class Box
{
var $contents;
function Box($contents) {
$this->contents = $contents;
}
function get_whats_inside() {
return $this->contents;
}
}
$mybox = new Box("Jack");
echo $mybox->get_whats_inside();
?>
A closer look at our blueprint shows it contains the variable $contents which is used to remember the contents of the box. It also contains two functions: Box and get_whats_inside.
When the box springs into existence, PHP will look for and execute the function with the same name as the class. That's why our first function has the same name as the class itself. The whole purpose of the Box function is to initialize the contents of the box.
The special variable $this is used to tell Box that contents is a variable that belongs to the whole class and not the function itself. The $contents variable only exists within the scope of the function Box. $this->contents is a variable which was defined as part of the overall class.
The function get_whats_inside returns the value stored in the class' contents variable, $this->contents.
When the entire script is executed the class Box is defined, new constructs a box and passes "Jack" to it's startup function. The initialization function, which has the same name as the class itself, accepts the value passed to it and stores it within the class's variable so that it's accessible to functions throughout the entire class.
Now we've got a nice, shiny new Jack in the Box.
To ask the box what it contains, the special get_whats_inside function was used. Functions defined in the class are known as methods; they act as a method for communicating with and manipulating the data within the box.
The nice thing about methods is that they allow us to separate all the class coding from our actual script.
We could save all of the class code in a separate file and then use include to import it into our script. Our scripts become more streamlined and, because we used descriptive names for our methods, anyone else reading our code can easily see our train-of-thought.
include("class.Box.php");
$mybox = new Box("Jack");
echo $mybox->get_whats_inside();
?>
Another benefit of methods is that it provides our box or whatever other objects we may build with a standard interface that anyone can use. We can share our classes with other programmers or even import them into our other scripts when the functionality they provide is needed.
include("class.Box.php");
$mybox = new Box("Suggestion");
echo $mybox->get_whats_inside();
?>
include("class.Box.php");
$mybox = new Box("Shoes");
echo $mybox->get_whats_inside();
?>
Beginning Object Oriented Programming in PHP - Extends
So far our example is only capable of telling us what its content is. We could add more methods to our class, but what if we were building extensions to someone else's class? We don't have to create an entirely new class to add new functionality... we can build a small extension class based on the original.
include("class.Box.php");
class ShoeBox extends Box
{
varr $size;
function ShoeBox($contents, $size) {
$this->contents = $contents;
$this->size = $size;
}
function get_shoe_size() {
return $this->size;
}
}
$mybox = new ShoeBox("Shoes", 10);
echo $mybox->get_whats_inside();
echo $mybox->get_shoe_size();
?>
With the extends keyword, our script now has access to a ShoeBox class which is based on our original Box class. ShoeBox has all of the same functionality as Box class but also has extra functions specific to a special kind of box.
The ability to write such modular additions to your code gives great flexibility in testing out new methods and saves time by reusing the same core code.
include("class.Box.php");
include("extentions.Shoe.php");
include("extentions.Suggestion.php");
include("extentions.Cardboard.php");
$mybox = new ShoeBox("Shoes", 10);
$mySuggestion = new SuggestionBox("Complaints");
$myCardboard = new CardboardBox('', "corrugated", "18in", "12in", "10in");
?>
Wednesday, October 17, 2007
History of php
Lerdorf initially created PHP to display his résumé and to collect certain data, such as how much traffic his page was receiving. Personal Home Page Tools was publicly released on 8 June 1995 after Lerdorf combined it with his own Form Interpreter to create PHP/FI (this release is considered PHP version 2).
Zeev Suraski and Andi Gutmans, two Israeli developers at the Technion IIT, rewrote the parser in 1997 and formed the base of PHP 3, changing the language's name to the recursive initialism PHP: Hypertext Preprocessor. The development team officially released PHP/FI 2 in November 1997 after months of beta testing.
Public testing of PHP 3 began and the official launch came in June 1998. Suraski and Gutmans then started a new rewrite of PHP's core, producing the Zend Engine in 1999. They also founded Zend Technologies in Ramat Gan, Israel, which actively manages the development of PHP.
In May 2000, PHP 4, powered by the Zend Engine 1.0, was released. The most recent update released by The PHP Group, is for the older PHP version 4 code branch which, as of May 2007, is up to version 4.4.7. PHP 4 will be supported by security updates until August 8, 2008.
On July 13, 2004, PHP 5 was released powered by the new Zend Engine II. PHP 5 included new features such as:
1. Improved support for object-oriented programming
2. The PHP Data Objects extension, which defines a lightweight and consistent interface for accessing databases
3. Performance enhancements
4. Better support for MySQL and MSSQL
5. Embedded support for SQLite
6. Integrated SOAP support
7. Data iterators
8. Error handling via exceptions
Currently, two major versions of PHP are being actively developed: 5.x and 4.4.x. The latest stable version, PHP 5.2.4, was released on Aug 30, 2007. On July 13, 2007, the PHP group announced that active development on PHP4 will cease by December 31, 2007, however, critical security updates will be provided until August 8, 2008. PHP 6 is currently under development, and is slated to release in conjunction with the decommission of PHP 4.
What is php
The main implementation is produced by The PHP Group and released under the PHP License. This implementation serves to define a de facto standard for PHP, as there is no formal specification.The most recent version of PHP is 5.2.4, released on 30 August 2007. It is considered to be free software by the Free Software Foundation.
Import xls into Mysql
to import xls file into mysql you can run this script, please make sure that xls file name is correct and placed in the same directory where you script file is.
$db_username="db_username"; //database user name
$db_password="db_password";//database password
$db_database="database_name"; //database name
$db_host="localhost";
mysql_connect($db_host,$db_username,$db_password);
@mysql_select_db($db_database) or die( "Unable to connect to database.");
$handle = fopen("test.xls", "r"); //test.xls excel file name
if ($handle)
{
$array = explode("\n", fread($handle, filesize("test.xls")));
}
$total_array = count($array);
$i = 0;
while($i < $total_array)
{
$data = explode(",", $array[$i]);
$sql = "insert into test values ('$data[0]','$data[1]')"; // i have two fields only , in oyour case depends on your table structure
$result = mysql_query($sql);
$i++;
}
echo "completed";
