http://www.developer.com/

Back to article

Elevate Your PHP Development with PHP 5.3's Powerful New Features


March 31, 2010

By typical development conventions, PHP 5.3 only qualifies as a "point release." However, the features packed into this new version are easily the most significant PHP development enhancements since PHP 5.0 was released in 2004. The powerful new PHP 5.3 features include namespace support, lambda functions and closures, late static binding, improved Windows support, and a host of syntactical additions. This article provides all the information you need to begin taking advantage of these PHP 5.3 goodies.

Namespace Support

The addition of namespaces is considered the most significant addition of the PHP 5.3 release. Namespaces provide developers with an effective means to organize code in a way that greatly diminishes the possibility of naming collisions (notably classes, functions, and constants) when integrating third-party code. Put into practical terms, you can now safely create a library capable of interacting with Amazon's A2S web service and namespace it using a unique moniker such as A2S. However, because namespace hierarchies are also supported, you probably should use a convention that guarantees uniqueness, such as Com\Wjgilmore\A2s.

Associating a file (say, a2s.php) to a namespace is easy; just use the namespace keyword like this:

<?php

  namespace Com\Wjgilmore\A2s;

  class AmazonAssociatesWebService
  {

    private $accessKeyID = ''
  
    function __construct($accessKeyID) {
      $this->accessKeyID = $accessKeyID;
    }

    function authenticate() {
      ...
    }

  }

?>


To use a namespaced class within your code, you first integrate the code using the usual require_once() statement, and then call the class by prefixing the class name with the namespace prefix, like this:

<?php
  require('a2s.php');
  $a2s = new Com\Wjgilmore\A2s\AmazonAssociatesWebService('secretkey');
?>


Because referencing lengthy namespace designations within your code will quickly become tedious, PHP 5.3 allows you to create an alias that can subsequently be used in place of the moniker, like this:

<?php
  require('a2s.php');
  
  use Com\Wjgilmore\A2s as A2s;

  $a2s = new A2s\AmazonAssociatesWebService('secretkey');
?>


Namespaces will no doubt play a major role in many aspects of the PHP language, including solutions such as the Zend Framework, which have relied upon necessarily long naming conventions (such as Zend_Db_Table_Row_Abstract) for classes.

Closures

Anonymous functions, also known as closures, play a significant role in languages such as JavaScript and Ruby. PHP 5.3 makes this powerful feature available to PHP developers, allowing you to write more succinct code. For instance, many PHP functions accept a function name as a variable, the latter known as a callback function. This callback function will execute and return its output to the caller. The caller can then use the output to perform other tasks. For instance, PHP's preg_replace_callback() function is handy for using a regular expression to search a string and replace any occurrences that have been transformed by a callback function with modified versions of the occurrences.

Here's how you would usepreg_replace_callback() to convert a string containing U.S.-localized dates to a more suitable European format prior to version 5.3:

$history = 'The Magna Carta was signed on 06-15-1215.';

echo preg_replace_callback("|(d{2})-(d{2})-(d{2})|", 'convertUsToEU', $history);

function convertUsToEU($matches) {
  return "{$matches[2]}-{$matches[1]}-{$matches[3]}";
}


This seems like quite a bit of formality just to swap a date around, right? Using closures, you can move the function definition into the preg_replace_callback() call, like this:

$history = 'The Magna Carta was signed on 06-15-1215.';

echo preg_replace_callback("|(d{2})-(d{2})-(d{2})|", 
                           function($matches) {   
                             return "{$matches[2]}-{$matches[1]}-{$matches[3]}"; 
                           },
                           $history
     );


Late Static Binding

The object-oriented development approach provides an easy and intuitive way to create hierarchical data structures, and to overload the properties of a parent class to fit the specific characteristics of its children. Consider the following example:

class Automobile {
  static $horn = "beep";
  static function honkHorn() {
    echo self::$horn;
  }
}

class GeneralLee extends Automobile {
  static $horn = "HONKITY HONK HONKY TONK!!!";
}


What do you believe will happen when the following command is called?

GeneralLee::honkHorn();


It seems logical that HONKITY HONK HONKY TONK!!! will be displayed, but in fact the meek beep will be returned instead. This is because PHP sees the $horn attribute's self prefix and presumes you've intended to output the attribute located within that particular class. To fix this issue, you can take advantage of PHP 5.3's new late-static binding feature: use the static keyword to reference the class attribute that will be displayed rather than the self keyword:

class Automobile {
  static $horn = "beep";
  static function honkHorn() {
    echo static::$horn;
  }
}

class GeneralLee extends Automobile {
  static $horn = "HONKITY HONK HONKY TONK!!!";
}


Upgraded MySQL Support

PHP's relationship with MySQL spans more than a decade, and the individual success of each technology is undoubtedly in part attributed to the respective communities' longstanding support for one another. As such, a great deal of attention is paid to PHP and MySQL performance issues. The latest proof of these efforts is present in PHP 5.3, with the introduction of a MySQL native driver for PHP, known as mysqlnd.

The mysqlnd driver doesn't change the way you interact with MySQL within your PHP applications; rather it improves performance thanks to its close integration with PHP and optimized approach to communicating with MySQL. This new driver also resolves licensing compatibility issues, which were introduced when MySQL changed its licensing guidelines a few years back. As a bonus, when you use this driver, you can to interact with a remote MySQL server without having to first install a MySQL client on the local server.

Ternary Shortcut

One of my favorite PHP syntax features is the ternary operator, which can significantly reduce the amount of code needed to carry out simple conditional tasks. Consider the following if statement:

if (isset($_POST['log_out_when_browser_closes'])) {
  $logUserOut = 1;
} else {
  $logUserOut = 0;
}


Using the ternary operator, you can reduce this statement to a single concise line:

$logUserOut = isset($_POST['log_out_when_browser_closes']) ?: 0;


Upgrading to PHP 5.3

If you haven't upgraded yet, what are you waiting for? Packages are available for all major platforms, including Windows, Mac OS X, and various Linux distributions.

Unfortunately, at the time of this writing Ubuntu did not offer PHP 5.3 as part of the official distribution, although several tutorials show you how to install it regardless. For instance, check out this tutorial and the accompanying comments for more information.

About the Author

Jason Gilmore is founder of EasyPHPWebsites.com. He is the author of several popular books, including "Easy PHP Websites with the Zend Framework," "Easy PayPal with PHP," and "Beginning PHP and MySQL, Third Edition."

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date