What’s new in PHP 5.3? Article

PHP 6 is just around the corner, but for developers who just can’t wait, there’s good news — many of the features originally planned for PHP 6 have been back-ported to PHP 5.3, a final stable release of which is due in the first half of this year.

This news might also be welcomed by those that wish to use some of the new features, but whose hosting providers will not be upgrading to version 6 for some time — hosting providers have traditionally delayed major version updates while acceptance testing is performed (read: the stability has been proven elsewhere first). Many hosting companies will probably delay upgrading their service offerings until version 6.1 to be released. A minor upgrade from 5.2.x to 5.3, however, will be less of a hurdle for most hosting companies.

This article introduces the new features, gives examples of where they might be useful, and provides demo code to get you up and running with the minimum of fuss. It doesn’t cover topics such as installing PHP 5.3 — the latest development release of which is currently available. If you’d like to play along with the code in this article, you should install PHP 5.3, then download the code archive. An article on installing PHP 5.3 can be
found on the Melbourne PHP Users Group web site.

Namespaces

Before the days of object oriented PHP, many application developers made use of verbose function names in order to avoid namespace clashes. WordPress, for example, implements functions such as wp_update_post and wp_create_user. The wp_ prefix denotes that the function pertains to the WordPress application, and reduces the chance of it clashing with any existing functions.

In an object oriented world, namespace clashes are less likely. Consider the following example code snippet, which is based on a fictional blogging application:

<?php 
class User {
 public function set( $attribute, $value ) { ... }
 public function save() { ... }
}
$user = new User();
$user->set('fullname', 'Ben Balbo');
$user->save();

In this example, the save method will not clash with any other method, as it is contained within the User class. There’s still a potential issue though: the User class might already be defined by some other part of the system if, for example, the blogging application runs within a content management system.
The solution to this issue is to use the new namespaces keyword. Taking the above code again, consider the following sample files:

<?php 
namespace MyCompany::Blog;
               
class User {
       
       public function set( $attribute, $value ) {
               $this->$attribute = $value;
       }
       
       public function save() {
               echo '<p>Blog user ' . $this->fullname . ' saved</p>';
       }

}

<?php
$user = new MyCompany::Blog::User();
$user->set(‘fullname’, ‘Ben Balbo’);
$user->save();

On the surface, the advantages offered by namespacing our function might not be immediately obvious — after all, we’ve simply changed MyCompany_Blog_User to MyCompany::Blog::User. However, we can now create a User class for the CMS using a different namespace:

<?php 
namespace MyCompany::CMS;

class User {

       public function set( $attribute, $value ) {
               $this->$attribute = $value;
       }
       
       public function save() {
               echo ‘<p>CMS user ‘ . $this->fullname . ‘ saved</p>';
       }

}

We can now use the classes MyCompany::Blog::User and MyCompany::CMS::User.

The use Keyword

Addressing classes using the full namespace still results in lengthy calls, and if you’re using lots of classes from the MyCompany::Blog namespace, you might not want to retype the whole path to the class every time. This is where the use keyword comes in handy. Your application will most likely use a number of different classes at any given time. Say, for example, the user creates a new post:

<?php 
use MyCompany::Blog;
$user = new Blog::User();
$post = new Blog::Post();
$post->setUser( $user );
$post->setTitle( $title );
$post->setBody( $body );
$post->save();

The use keyword is not restricted to defining namespaces in which to work. You can also use it to import single classes to your file, like so:

<?php 
use MyCompany::Blog::User;
$user = new User();
Namespace Aliases

Earlier, I pointed out that one advantage of namespacing is the ability to define more than one class with the same name in different namespaces. There will obviously be instances where those two classes are utilized by the same script. We could just import the namespaces, however, we also have the option of importing just the classes. To do so, we can use namespace aliasing to identify each class, like so:

<?php 
use MyCompany::Blog::User as BlogUser;
use MyCompany::CMS::User as CMSUser;

$bloguser = new BlogUser();
$bloguser->set(‘fullname’, ‘John Doe’);
$bloguser->save();

$cmsuser = new CMSUser();
$cmsuser->set(‘fullname’, ‘John Doe’);
$cmsuser->save();

Class Constants

Constants are now able to be defined at the class level! Note that class constants are available when you’re importing namespaces, but you cannot import the constant itself. Here’s an example of how we might use them:

<?php 
namespace MyCompany;

class Blog {
       const VERSION = ‘1.0.0’;
}

<?php
echo ‘<p>Blog bersion ‘ . MyCompany::Blog::VERSION . ‘</p>';

use MyCompany::Blog;
echo ‘<p>Blog version ‘ . Blog::VERSION . ‘</p>';
       
use MyCompany::Blog::VERSION as Foo;
echo ‘<p>Blog version ‘ . Foo . ‘</p>';  
This will result in the following output:
Blog bersion 1.0.0
Blog version 1.0.0
Blog version Foo

Namespaced Functions

The use of static class methods has deprecated the use of functions in the object oriented world in which we now live. However, if you do need to add a function to your package, it too will be subject to namespacing!

Here’s an example:

<?php 
namespace bundle;
function foo() { echo '<p>This is the bundled foo</p>'; }
foo(); // This prints 'This is the bundled foo'

<?php
function foo() { echo ‘<p>This is the global foo</p>'; }
require( ‘lib/bundle.class.php’);
bundle::foo(); // This prints ‘This is the bundled foo’
foo(); // This prints ‘This is the global foo’

The Global Namespace

The global namespace is an important consideration when you’re dealing with functions. In the previous example, you’ll notice that there’s no direct way of calling the global foo function from within the bundle code.

The default method of resolving calls to functions is to use the current namespace. If the function cannot be found, it will look for an internal function by that name. It will not look in other namespaces automatically.

To call the global foo function from within the bundle namespace, we need to target the global namespace directly. We do this by using a double colon:

<?php 
namespace bundle;
function foo() { echo '<p>This is the bundled foo</p>'; }
foo(); // This prints 'This is the bundled foo'
::foo(); // This prints 'This is the global foo'

Autoloading Namespaced Classes

If you’re defining the magic __autoload function to include class definition files on demand, then you’re probably making use of a directory that includes all your class files. Before we could use namespaces, this approach would suffice, as each class would be required to have a unique name. Now, though, it’s possible to have multiple classes with the same name.

Luckily, the __autoload function will be passed the fully namespaced reference to the class. So in the examples above, you might expect a call such as:

__autoload( 'MyCompany::Blog::User' );

You can now perform a string replace operation on this parameter to convert the double colons to another character. The most obvious substitute would be a directory separator character:

function __autoload( $classname ) {  
       $classname = strtolower( $classname );  
       $classname = str_replace( '::', DIRECTORY_SEPARATOR, $classname );  
       require_once( dirname( __FILE__ ) . '/' . $classname . '.class.php' );  
}

This would take the expected call above and include the file ./classes/mycompany/blog/user.class.php.

Late Static Binding

Late static binding provides the ability for a parent class to use a static method that has been overridden in a child class. You might imagine this would be the default behaviour, but consider the following example:

<?php  
 
class ParentClass {  
     
       static public function say( $str ) {  
               self::do_print( $str );  
       }  
 
       static public function do_print( $str ) {  
               echo "<p>Parent says $str</p>";  
       }  
 
}  
 
class ChildClass extends ParentClass {  
         
       static public function do_print( $str ) {  
               echo "<p>Child says $str</p>";  
       }  
 
}  
 
ChildClass::say( 'Hello' );

You would probably expect this to return "Child says Hello". While I understand why you might expect this, you’ll be disappointed to see it return "Parent says Hello".

The reason for this is that references to self:: and __CLASS__ resolve to the class in which these references are used. PHP 5.3 now includes a static:: reference that resolves to the static class called at runtime:

        static public function say( $str ) {  
               static::do_print( $str );  
       }

With the addition of the static:: reference, the script will return the string "Child says Hello".

__callstatic

Until now, PHP has supported a number of magic methods in classes that you’ll already be familiar with, such as __set, __get and __call. PHP 5.3 introduces the __callstatic method, which acts exactly like the call method, but it operates in a static context. In other words, the method acts on unrecognized static calls directly on the class.

The following example illustrates the concept:

<?php  
 
class Factory {  
 
       static function GetDatabaseHandle() {  
               echo '<p>Returns a database handle</p>';  
       }  
 
       static function __callstatic( $methodname, $args ) {  
               echo '<p>Unknown static method <strong>' . $methodname . '</strong>' .  
                       ' called with parameters:</p>';  
               echo '<pre>' . print_r( $args, true ) . '</pre>';  
       }  
}  
 
Factory::GetDatabaseHandle();  
Factory::CreateUser();  
Factory::CreateBlogPost( 'Author', 'Post Title', 'Post Body' );
Variable Static Calls

When is a static member or method not static? When it’s dynamically referenced, of course!

Once again, this is an enhancement that brings object functionality to your classes. In addition to having variable variables and variable method calls, you can now also have variable static calls. Taking the factory class defined in the previous section, we could achieve the same results by invoking the following code:

$classname = 'Factory';  
$methodname = 'CreateUser';  
$classname::$methodname();  
 
$methodname = 'CreateBlogPost';  
$author = 'Author';  
$posttitle = 'Post Title';  
$postbody = 'Post Body';  
 
$classname::$methodname( $author, $posttitle, $postbody );  
You can create dynamic namespaces like so:  
<?php  
require_once( 'lib/autoload.php' );  
 
$class = 'MyCompany::Blog::User';  
$user = new $class();  
$user->set('fullname', 'Ben Balbo');  
$user->save();

These little touches can make your code more readable and allow you full flexibility in an object oriented sense.

MySQL Native Driver

Until version 5.3 of PHP, any interaction with MySQL usually occurred in conjunction with libmysql — a MySQL database client library.

PHP 5.3’s native MySQL driver has been designed from the ground up for PHP and the ZEND engine, which brings about a number of advantages. Most obviously, the native driver is specific to PHP, and has therefore been optimised for the ZEND engine. This produces a client with a smaller footprint and faster execution times.

Secondly, the native driver makes use of the ZEND engine’s memory management and, unlike libmysql, it will obey the memory limit settings in PHP.

The native driver has been licensed under the PHP license to avoid licensing issues.

Additional OpenSSL Functions

If you’ve ever had to perform any OpenSSL-related actions in your scripts, (such as generating a Diffie Hellman key or encrypting content) you’ll either have performed this operation in user-land, or passed the request to a system call.

A patch to the OpenSSL functionality in PHP 5.3 provides the extra functions required to perform these actions through the OpenSSL library, which not only makes your life easier and your applications faster, but allows you to reuse the proven code that comes with OpenSSL.

This will be great news for anyone that’s currently working with OpenID.

Improved Command Line Parameter Support

Hopefully, you’ll be aware of the fact that PHP is more than just a scripting language for the Web. The command line version of PHP runs outside of the web server’s environment and is useful for automating system and application processes.

For example, the getopt function of PHP has been around for a while, but has been limited to a number of system types; most commonly, it didn’t function under a Windows operating system environment.

As of PHP 5.3, the getopt function is no longer system dependent. Hooray!

XSLT Profiling

XSLT is a complex beast, and most users of this templating mechanism will be familiar with xsltproc’s profiling option. As of PHP 5.3, you can profile the transforms from within your PHP scripts. This snippet from the example code that accompanies this article gives you an idea of how we might use it:

$doc = new DOMDocument();  
$xsl = new XSLTProcessor();  
 
$doc->load('./lib/collection.xsl');  
$xsl->importStyleSheet($doc);  
 
$doc->load('./lib/collection.xml');  
$xsl->setProfiling("/tmp/xslt-profiling.txt");  
echo $xsl->transformToXML($doc);  
 
echo '<h2>Profile report</h2>';  
echo '<pre>' . file_get_contents( '/tmp/xslt-profiling.txt' ) . '</pre>';

The information produced by the profile will look something like this:

number    match    name   mode     Calls   Tot  100us  Avg  
0         collection                    1       4       4  
1         cd                            2       1       0  
 
          Total                         3       5
New Error Levels

PHP is certainly a language that has a few, er, quirks. For example, why doesn’t E_ALL include all error levels?

Well now it does! Yes, PHP 5.3 now includes E_STRICT as part of E_ALL.

Furthermore, while E_STRICT used to report on both the usage of functionality that might become deprecated in the near future, and on bad programming practices such as defining an abstract static method, in PHP 5.3, these two errors are split into E_DEPRECATED and E_STRICT respectively, which makes a lot more sense.

Other Minor Improvements

There’s a handful of other improvements coming in PHP 5.3 that either don’t warrant an entire section in this article, or were untestable at the time this article was written, such as:

  • Sqlite3 support via the ext/sqlite extension
  • SPL’s DirectoryIterator, which now implements ArrayAccess
  • Two news functions: array_replace and array_replace_recursive. While these functions were undefined when tested under PHP 5.3.0, the C code that implements them suggests that they will contain similar functionality to array_merge. One exception, however, is that the array_replace function will only update values in the first array where the keys match in both arrays. Any keys that are present in the second array but don’t appear in the first will be ignored.
Summary

PHP 5.3 contains much functionality that was originally slated for inclusion in PHP 6, which takes it from being a minor upgrade to a significant release that every PHP developer should start thinking about. We touched on most of the features in this article, and looked at some code that demonstrates how you might go about using these new features.

Don’t forget to download the code archive that accompanies this article, and have fun living on the edge!

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • dskanth

    Thanks for the information… very useful…