PHP DevCenter

oreilly.comSafari Books Online.Conferences.

We've expanded our LAMP news coverage and improved our search! Search for all things LAMP across O'Reilly!

Search
Search Tips

advertisement

Listen Print Discuss Subscribe to PHP Subscribe to Newsletters

Why PHP 5 Rocks!

by Adam Trachtenberg, author of Upgrading to PHP 5
07/15/2004

PHP 5, which was released earlier this week, is the first major release of PHP in years to focus on new features.

While one of the key goals behind PHP 3 was increasing PHP/FI 2.0's performance and efficiency, at the same time it introduced a whole new set of functionality.

That was back in 1998.

PHP 4 provided another speed burst, as it introduced the Zend Engine. However, the majority of PHP 4's changes were behind the scenes. Those features allowed more people than ever to use PHP, but it didn't provide them with more tools to build their sites.

Finally, after six years, the community has revisited the legacy baggage that made tackling some problems unnecessarily difficult.

In particular, PHP 4's version of object-oriented programming (OOP) lacks many features, the MySQL extension doesn't support the new MySQL 4.1 client protocol, and XML support is a hodgepodge.

Fortunately, PHP 5 improves on PHP 4 in three major areas:

Related Reading

Upgrading to PHP 5
By Adam Trachtenberg

  • Object-oriented programming
  • MySQL
  • XML

These items have all been completely rewritten, turning them from limitations into star attractions. While these changes alone warrant a new version of PHP, PHP 5 also provides a plethora of other new features.

In this article, I highlight seven of my favorite PHP 5 features. These features allow your PHP 5 code to frequently be shorter, more elegant, and more flexible than ever before.

1. Robust Support for Object-Oriented Programming

Ever since Zeev and Andi's late-night OOP hack, PHP programmers have clamored for an increasing amount of OO features. However, neither PHP 3 nor PHP 4 truly incorporates objects into its core.

With PHP 5, PHP programmers can at last stop apologizing for PHP's krufty OO support. It offers:

  • Constructors
  • Destructors
  • Public, protected, and private properties and methods
  • Interfaces
  • Abstract classes
  • Class type hints
  • Static properties and methods
  • Final properties and methods
  • A whole suite of magical methods

Additionally, objects are now both assigned--and passed--by reference instead of by value, so the necessity to liberally sprinkle ampersands throughout your code is no more.

If you're a person who enjoys web programming using objects and patterns, then these features alone will make your year. However, PHP 5's just getting started.

2. A Completely Rewritten MySQL Extension

The MySQL database is PHP's partner in crime. Many developers power their web sites with MySQL, yet the MySQL extension is showing its age. In retrospect, some design decisions weren't the best solutions after all.

Also, the latest versions of MySQL, 4.1 and 5.0, introduce many new features, some of which require significant changes to the extension. As a result, PHP 5 comes with a completely new and improved MySQL extension. Dubbed MySQLi, for MySQL Improved. It offers:

  • Prepared statements
  • Bound input and output parameters
  • SSL connections
  • Multi-query functions

MySQLi even takes advantage of PHP 5's new object-oriented support to provide an OO interface to MySQL. On top of that, the latest versions of MySQL now enable subselects, transactions, and replication.

3. A Suite of Interoperable XML Tools

PHP 5 fixes the major problems in PHP 4's XML extensions. While PHP 4 allows you to manipulate XML, its XML tools are only superficially related. Each tool covers one part of the XML experience, but they weren't designed to work together, and PHP 4 support for the more advanced XML features is often patchy.

Not so in PHP 5.

The new XML extensions:

  • Work together as a unified whole.
  • Are standardized on a single XML library: libxml2.
  • Fully comply with W3 specifications.
  • Efficiently process data.
  • Provide you with the right XML tool for your job.

Additionally, following the PHP tenet that creating web applications should be easy, there's a new XML extension that makes it simple to read and alter XML documents. The aptly named SimpleXML extension allows you to interact with the information in an XML document as though these pieces of information are arrays and objects, iterating through them with for-each loops, and editing them in place merely by assigning new values to variables.

In short, SimpleXML kicks ass!

If you know the document's format ahead of time, such as when you're parsing RSS files, REST results, and configuration data, SimpleXML is the way to go.

And if you're a DOM fan, you'll be pleasantly surprised with PHP 5's DOM extension, which is light-years beyond what you're using in PHP 4.

4. An Embedded Database with SQLite

While MySQL is greater than ever, it's actually "too much database" for some jobs. SQLite is an embedded database library that lets you store and query data using an SQL interface without the overhead of installing and running a separate database application.

When your application needs a server-side storage mechanism but you can't rely upon the presence of a specific database, turn to SQLite. It correctly handles locking and concurrent accesses, the two big headaches with homebrewed flat files.

PHP 5 bundles SQLite, providing developers with a database that's guaranteed to work on all PHP 5 installations. Despite the name, SQLite is nowhere close to a "lite" database. It supports:

  • Transactions
  • Subqueries
  • Triggers
  • And many other advanced database features

You can even write user-defined functions in PHP and call them from within SQLite. This is by far and away the coolest feature available in any PHP database extension.

5. Cleaner Error Handling with Exceptions

PHP 5 offers a completely different model of error checking than what's available in PHP 4. It's called exception handling. With exceptions, you're freed from the necessity of checking the return value of every function. Instead, you can separate programming logic from error handling and place them in adjoining blocks of code.

Exceptions are commonly found in object-oriented languages such as Java and C++. When used judiciously, they streamline code, but when used willy-nilly, they create spaghetti code.

Right now, only a few PHP extensions use exceptions, but they're slowly being phased in. However, they're available today for any PHP code you write.

6. A First-Class SOAP Implementation

SOAP is a key component of the fast-growing web services field. This extension lets developers create SOAP clients with or without a Web Services Description Language (WSDL) file, and also implement SOAP servers in PHP.

PHP 4's SOAP support is only fair. While there are a few SOAP packages, the most mature ones are written in PHP instead of C. Therefore, they are slow, and you have to download and install them yourself.

With PHP 5, there's finally a usable SOAP extension written in C. Currently, this extension implements most, but not all, of SOAP 1.2. This is a significant improvement over previous C extension, and future pieces will be added in time.

Particularly in comparison with .NET and Java, PHP's SOAP support has always lagged behind the curve. Whether you love or hate SOAP, PHP needs to offer a first-class SOAP extension, and I'm excited to finally see some momentum in this direction.

7. Iterators

Iterators are a completely new PHP 5 feature. They allow you to use a for-each loop to cycle through different types of data: directory listings, database results, and even XML documents. SPL -- Standard PHP Library -- is a collection of iterators that provide this functionality and also filter, limit, cache, and otherwise modify iterator results.

Iterators are an incredibly handy way to abstract away messy details from your code.

For example, the DirectoryIterator turns directory iteration from this:


$dir = opendir($path);
while (false !== ($file = readdir($dir))) {
    print "$file\n";
}
closedir($dir);

Into this:


foreach (new DirectoryIterator($path) as $file) {
    print "$file\n";
}

There are no directory handles to mess about with, nor ugly conditions to check inside a while loop.

These are my top seven favorite features of PHP 5, but they're by no means the only ones. Besides what I've already highlighted, PHP 5 also offers:

  • Enhanced streams, wrappers, and filters.

    First introduced in PHP 4.3, streams are an underutilized part of PHP. They allow you to place a file interface on reading and writing data using protocol-specific objects known as wrappers. Streams also let you modify the data flowing through them by attaching filters.

  • Code introspection using the Reflection classes.

    This set of classes lets you examine classes, methods, parameters, and more, to discover object attributes. It is now simple and easy to create PHP class browsers, debuggers, and other tools that rely on gathering details about objects and functions.

  • Compliant HTML output thanks to Tidy.

    The Tidy extension makes it easy to ensure that your output is valid HTML and XHTML. Its smart parser brings even the most unruly of files into compliance with the latest W3C specifications.

  • Superior command-line processing.

    The PHP5 command-line version now allows individual line processing, similar to Perl and awk. You can specify code to be run at the beginning, on, and at the end of each line in a file.

I hope you've found this quick tour around PHP 5 useful. As you can see, PHP 5 is leaps and bounds better than before. I'm sure you'll find all sorts of cool ways to incorporate its features into your programs.

Adam Trachtenberg is the manager of technical evangelism for eBay and is the author of two O'Reilly books, "Upgrading to PHP 5" and "PHP Cookbook." In February he will be speaking at Web Services Edge 2005 on "Developing E-Commerce Applications with Web Services" and at the O'Reilly booth at LinuxWorld on "Writing eBay Web Services Applications with PHP 5."


Return to the PHP DevCenter.


O'Reilly Media, Inc., will soon release (July 2004) Upgrading to PHP 5.

  • Sample Chapter 4, SQLite, is available free online.

  • You can also look at the Table of Contents, the Index, and the Full Description of the book.

  • For more information, or to order the book, click here.


Though it's just released, what new features in PHP 5 have you ready to upgrade?
You must be logged in to the O'Reilly Network to post a talkback.
Post Comment
Full Threads Newest First

Showing messages 1 through 15 of 15.

  • Unfortunately, PHP5 sucks no less than PHP4
    2004-07-16 14:49:01  zgoda [Reply | View]

    It still doesn't have native unicode support, so all this XML buzz is just that -- a buzz. In modern world lacking of unicode awareness makes any solution incomplete.
    • Adam Trachtenberg photo Unfortunately, PHP5 sucks no less than PHP4
      2004-07-16 15:40:31  Adam Trachtenberg | O'Reilly Author [Reply | View]

      Unicode support is on my list of things that would be great to add to PHP 6. :)

      But seriously, my Perl core language friends told me that incorporating Unicode into Perl was damn difficult and opened up all sorts of issues. So, while Unicode is necessary, it needs to be done correctly, and with all the new features in PHP 5, I don't think now is the right time.

      Also, PHP 5 uses libxml2 to power its XML extensions, so you can use UTF-8 and other character encodings in your XML documents. You just may need to jump through a few hoops to get your data in there.
      • Unfortunately, PHP5 sucks no less than PHP4
        2004-07-17 00:05:41  zgoda [Reply | View]

        The problem is, that these "hoops" require at least iconv extension (which is is not build by default) and these "hoops" may be quite large if you have mix of, say, Turkish and Russian in your XML content.
        • Adam Trachtenberg photo Unfortunately, PHP5 sucks no less than PHP4
          2004-07-17 00:25:33  Adam Trachtenberg | O'Reilly Author [Reply | View]

          Actually, as of PHP 5, iconv is now enabled by default. That's one of the few new things I didn't mention in my article.

          And, yes, the hoops are larger when you're mixing non-Western character sets. But what are you going to do?

          I'm sure if you were to produce a patch, the PHP community would gladly accept it. After all, two of the key developers of PHP are from Israel, and I know Hebrew isn't easily represented in ASCII.
    • Unfortunately, PHP5 sucks no less than PHP4
      2006-05-08 10:25:36  zorgalina [Reply | View]

      That is not the only reason why PHP sucks, but I agree with you, without unicode support PHP should not be a first choice for web programming.
  • No namespaces?
    2004-07-16 15:17:03  arunp [Reply | View]

    C++, Java, C#, Perl, Python, Ruby all have namespaces. Why doesn't PHP need namespaces?
    • Adam Trachtenberg photo No namespaces?
      2004-07-16 15:39:52  Adam Trachtenberg | O'Reilly Author [Reply | View]

      PHP 5 originally had namespaces, but they were dropped during the beta process.

      There are certainly lots of people who would like namespaces in PHP, but that's not a feature that made it into PHP 5.
      • No namespaces?
        2004-07-18 03:15:53  otto [Reply | View]

        PHP clearly lacks a benevolent dictator. Design by committee hardly ever works.
  • PostgreSQL has plphp, btw
    2004-07-17 20:11:43  smarlowe [Reply | View]

    PostgreSQL can also have user defined functions / stored procs written in PHP. Just FYI. I know it's not a "new" feature, but just wanted to point out that SQL Lite isn't the only db engine that has this.
    • Adam Trachtenberg photo PostgreSQL has plphp, btw
      2004-07-19 08:22:25  Adam Trachtenberg | O'Reilly Author [Reply | View]

      Cool! I never knew that. I don't play around much with PostgreSQL. Thanks.
  • some questions
    2004-07-18 03:19:08  riffraff [Reply | View]

    I never found this in php5 presentations:
    - are classes objects ?
    - are classes locked or open (like ruby,smalltalk)?
    - can you define your own metaclasses or
    - can you control the allocation+initialization of an object (like python,ruby,smalltalk) or just init like java?
    - can you do mixin programming in php5 ?

    - how good is the performance of runtime class checking of arguments to methods?
    - there are nifty tricks to make it faster than an attribute lookup at any call?
    • some questions
      2004-08-16 13:15:05  GassertH [Reply | View]

      I'm no expert of Ruby or Smalltalk, but I'll try to answer. I think the PHP5 developers thought much more of Java (Sun is becoming an important PHP player..) than of these other languages. Let's not judge that for the moment ,)
      PHP, and let's state that clearly, is not an object-oriented language _only_. The majority of its user base most probably does not use OOP. The new OO-features are a step forwards, but certainly a pragmatic user-focused one. Do not look for "highbrow" OO-theoretic stuff in PHP. Consequence: I could directly write a big NO as an overall answer here :)

      # - are classes objects ?
      There is no class "class", if you mean that. But with the new Reflection API and by the means of "$o = new $someClassName();" you should be able to do most of the things you could do with the class "class" in Java.
      I think you could say there are no metaclasses.

      # are classes locked or open (like ruby,smalltalk)?
      I guess they're locked, I do no know of a way to alter a loaded class. Not sure if I understand the question, though.

      # can you define your own metaclasses or
      No metaclasses, I still think

      # can you control the allocation+initialization of an object?
      no. no object-oriented/-aware way to deal with things like memory usage and time consumption.

      # can you do mixin programming in php5 ?
      there's only "ordinary" inheritance.

      # how good is the performance of runtime class checking of arguments to methods?
      define "good" while I do a little benchmarking :)

      # there are nifty tricks to make it faster than an attribute lookup at any call?
      I did not understand this question? What do you refer to by "it"?

      • some questions
        2004-08-22 08:24:46  GassertH [Reply | View]

        Perhaps http://pecl.php.net/package/classkit should be mentioned here. It's an extension that allows you to add, remove, rename, and redefine class methods at runtime.
  • interfaces &__autoload
    2005-01-22 12:27:15  hooda [Reply | View]

    I have been told that if I use interfaces in PHP 5 that it is important to define the class before you instantiate the object.

    Does this mean that I will run into trouble if I use __autoload to load my class definitions when I instantiate an object?
    • interfaces &__autoload
      2006-07-06 00:51:44  filip_gg [Reply | View]

      You can check on your interface with this function right here:

      interface_exists(string $interface, bool $autoload=TRUE)

      Returns TRUE if $interface is
      defined in the current script.
      Unless $autoload is set to
      FALSE, this function will
      attempt to invoke
      __autoload() (if defined)


Tagged Articles

Post to del.icio.us

This article has been tagged:

php

Articles that share the tag php:

Understanding MVC in PHP (477 tags)

The PHP Scalability Myth (123 tags)

The Dynamic Duo of PEAR::DB and Smarty (53 tags)

PHP Form Handling (43 tags)

Very Dynamic Web Interfaces (39 tags)

View All

php5

Articles that share the tag php5:

Understanding MVC in PHP (17 tags)

Programming eBay Web Services with PHP 5 and Services_Ebay (5 tags)

Three-Tier Development with PHP 5 (5 tags)

Using PHP 5's SimpleXML (4 tags)

Why PHP 5 Rocks! (2 tags)

View All

programming

Articles that share the tag programming:

Rolling with Ruby on Rails (1374 tags)

Very Dynamic Web Interfaces (279 tags)

Ajax on Rails (231 tags)

Understanding MVC in PHP (202 tags)

A Simpler Ajax Path (186 tags)

View All

Sponsored Resources

  • Inside Lightroom
Advertisement

Sponsored by:

O'Reilly Media

©2009, O'Reilly Media, Inc.
(707) 827-7000 / (800) 998-9938
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
About O'Reilly
Academic Solutions
Authors
Contacts
Customer Service
Jobs
Newsletters
O'Reilly Labs
Press Room
Privacy Policy
RSS Feeds
Terms of Service
User Groups
Writing for O'Reilly
Content Archive
Business Technology
Computer Technology
Google
Microsoft
Mobile
Network
Operating System
Digital Photography
Programming
Software
Web
Web Design
More O'Reilly Sites
O'Reilly Radar
Ignite
Tools of Change for Publishing
Digital Media
Inside iPhone
O'Reilly FYI
makezine.com
craftzine.com
hackszine.com
perl.com
xml.com

Partner Sites
InsideRIA
java.net
O'Reilly Insights on Forbes.com