Eagerly Anticipating PHP 5.3

We at Genius.com, like many in the PHP community, anxiously await the release of PHP 5.3. The new version will offer significant improvements ranging from rounding out the functionality of the object model to adding some common data structures to the Standard PHP Library (SPL). You can find an overview of the changes on PHP.net, including a detailed upgrading guide and the full changelog. Here is a list of the major features and some of our favorite articles covering each of them (with a bit of our own commentary sprinkled on top):

Late Static Binding

As practitioners of agile development principles, we employ practices from Scrum, Lean, and XP. One technique we’ve borrowed from XP is the use of static creation methods instead of calling constructors directly. The absence of late static binding before PHP 5.3 in conjunction with the use of static creation methods leads to a great deal of copy-pasted code, as in the following example:

<?php
abstract class BaseClass
{
    protected function construct($arg)
    {
        // Perform intialization, dependent on $arg
    }
}
 
class Implementation1 extends BaseClass
{
    public static function getNew()
    {
        return new self('value1');
    }
}
 
class Implementation2 extends BaseClass
{
    public static function getNew()
    {
        return new self('value2');
    }
}
?>

With the new static resolution of PHP 5.3, we would be able to write the same functionality with the following code:

<?php
abstract class BaseClass
{
    protected function construct($arg)
    {
        // Perform intialization, dependent on $arg
    }
 
    public static function getNew()
    {
        return new self(static::INITIALIZATION_VAR);
    }
}
 
class Impl1 extends BaseClass
{
    const INITIALIZATION_VAR = 'value1';
}
 
class Impl2 extends BaseClass
{
    const INITIALIZATION_VAR = 'value2';
}
?>

Granted, this may not seem like a significant change, but it does a couple of important things for us. First, it reduces the redundancy required to redeclare the getNew() method in each subclass. This does not have much effect in our trivial example, but the savings add up if there are dozens of child classes all extending from the parent class. Additionally, it puts the getNew() method in a place that makes it more explicit to the developer when something outside of the typical instantiation is being done. Whereas before the only option to tell if the object did anything special was to look at a few more child classes to make sure all the getNew() methods matched, now you can simply look to see if the child method overrides the parent.

Dynamic Static

Encountering the extraordinarily confusingly-named “Paamayim Nekudotayim” error is one of the most frustrating interactions we have had with PHP at Genius. Given that none of the developers here speak Hebrew, the first time we ran into this error resulted in some extremely puzzled engineers. While nearly any misuse of the double colon (::) operator will result in a “Paamayim Nekudotayim” error, the one we come across most often involves trying to use variable interpolation to dynamically set the name for a class on which to execute a static method call. The code below shows our current, somewhat clumsy, solution to the problem:

<?php
    $className = 'StaticClassName';
    $evalCommand = '$result = '. $className .'::staticFunctionName();';
    eval($evalCommand);
    return $result;
?>

Contrasted with the following code snippet using the new feature available in 5.3, the relative cleanliness of the new approach overwhelms:

<?php
    $className = 'StaticClassName';
    return $className::staticFunctionName();
?>
  • IBM DeveloperWorks article by John Mertic

    This article provides an excellent overview of most of the OOP-related changes in the new version. It also touches on the “dynamic static” function call.

Namespaces

  • PHP.net documentation specific to using namespaces (don’t miss the handy FAQ!)
  • IBM DeveloperWorks article by John Mertic

    Mertic’s article provides, once again, an excellent overview of the new PHP feature. He covers the creation, use, and aliasing of namespaces in addition to typical use cases and a few tricky things to watch out for.

  • php 5.3 namespace/exception gotcha by Jason Frame

    Jason presents an interesting point to consider related to exceptions thrown in namespaced code. This article will probably save a few subtle bugs sometime down the road.

Lambda Functions/Closures

  • PHP.net documentation covering anonymous functions
  • IBM DeveloperWorks article by John Mertic

    This excellent article from Mr. Mertic gives a concise description of what lambda functions and closures are and when you should use them.

  • [js.php] A JavaScript Object Like PHP Class by Andrea Giammarchi

    The addition of closures into PHP in combination with the magic __call() method allows you to do some extremely interesting things with the object model. In this article, the author constructs a JavaScript-like class that allows the addition of public methods on the fly via closures, array-style access to class members, and the ability to serialize itself to JSON.

Other Niceties

  • PHP.net documentation for SPL Data Structures

    SPL grows in this release to include a few commonly-used data structures such as implementations of a stack and queue based upon a doubly-linked list, minimum and maximum heaps based upon a base heap class, and a priority queue. Having standard implementations of elementary data structures like these can be a huge boon, allowing community members to save time by not having to reimplement standard functionality as well as offering a good jumping-off point for the implementation of more complex data structures.

  • IBM DeveloperWorks article about Phar archives by John Mertic

    Phar, a packaging format similar in concept to Jar archives from Java, facilitates the simple deployment and distribution of entire applications or libraries by packaging everything into a single file. This can ease the maintenance burden of both developers and the build & release engineers, since incorporating outside frameworks will become easier as will releasing your own application.

  • The DateTime class gains several new utility functions, including add(), sub(), createFromFormat(), and getLastErrors()
  • A few new core functions of note have been added in PHP 5.3, including lcfirst() and str_getcsv()

Conclusion

All in all, PHP 5.3 brings a lot of exciting improvements to the table and developers at Genius are chomping at the bit to get access to the new language features. We thank and congratulate the PHP team for their development up to the current release candidate and look forward to the stable release!

  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Twitter
  • Google Bookmarks
  • DZone
  • HackerNews
  • LinkedIn
  • Reddit
  • Michael Gauthier

    GOod summary. For dynamic static calling I think you can use call_user_func() with an array style callback.

    call_user_func(array($class_name, ‘someMethod’));

    The new syntax in 5.3 looks even better though!

  • http://trephine.org/t/index.php?title=Home Jim R. Wilson

    Great summary, thanks!

    Building on what Michael said, you could also use call_user_func( “{$class_name}::someMethod” ); If I recall, there is some discrepancy between PHP 5.1 and PHP 5.2 with regards to the array() nomenclature Michael recommends.

    I do know for sure that within the MediaWiki code base, the string method above is used exclusively.

  • Robert

    They get an “A” for the suckiest version of a namespace. The slash!

    use PEAR\Date;

  • Kevin

    Yeesh, I agree with Robert on that being the suckiest version of a namespace. They could have at least used a forward slash even, not sure why you’d ever use a backslash as the delimiter on it since most programmers are used to that being the escape character.

  • mario

    This must be a WordPress blog run by a Windows “programmer”.
    You really like the namespace syntax with backslashes, do you?

  • http://www.genius.com Ryan Ausanka-Crues

    Haha, some of us use Windows, some use Linux, some use Mac but only one of us can be considered a Windows programmer (and it’s not Bill). Our eagerness to see namespaces in PHP should not be read as an endorsement of using the backslash character as a delimiter. We totally agree that the backslash is one of the worst choices for a delimiter. If I had more time right now I’d research through the annals of php.net to try to find out why such an interesting choice was made. There are so many more sane options: period, underscore, even the previously mentioned forward slash is at least marginally better.

    Also, thank you Jim and Michael for the call_user_func() idea. I’m not sure if we looked at that before but I think we started using our annoying eval notation when we were on PHP 5.0.5 and never looked back to see if there was a more elegant way to do it during our subsequent upgrades. My recollection is fuzzy, but I think we ran into problems with call_user_func() in 5.0.5.