John Squibb

Fun with PHP 5.3

02 September, 2009

Version 5.3 has been out a little over two months, so it's nigh time I dug into into it! It's surprising that I've waited this long to get around to installing it, as it contains some tidbits that I have been eagerly awaiting since talk about PHP 6 began a couple years ago. In addition to the usual bug fixes, this version includes support for two features of particular interest to me: namespaces and variable static method calls.

Variable Static Method Calls

One of the biggest annoyances prior to 5.3, was that one couldn't call the static method of a class using a variable. The following code, for example, just plain would not work:

<?php

$variable
::static_method();

Toggle plain-text

It is a very small change, but it makes all the difference in the world when using factories, builders, and singletons. Consider the following animal classes:

<?php

class Cow
{
    public static 
$name 'Herbert';
    
    public static function 
speak()
    {
        print 
'moo';
    }
}

class 
Pig 
{
    public static 
$name 'Leon';
    
    public static function 
speak()
    {
        print 
'oink';
    }    
}

class 
Cat 
{
    public static 
$name 'Oedipus';
    
    public static function 
speak()
    {
        print 
'Meow';
    }
}

//animals!
$animals = array('Cow''Pig''Cat');

//show variable static function calls
foreach ($animals as $animal)
{
    
//make silly sounds
    
print $animal::$name ':';
    
$animal::speak();
    print 
"\n";
};

Toggle plain-text

If you have ever used the singleton pattern, you know that the key to fetching object instances is to call the instance() or similarly named function statically. Prior to 5.3, it was impossible to dynamically call upon singletons without using trickery, such as the call_user_func or call_user_func_array methods. Now, it is very easy to simply use the syntax demonstrated above.

Another situation where the dynamic call proves useful is when trying to fetch the constants of a particular class. In the past, the developer was forced to instantiate the class, and then use a custom function to fetch the constant and return it, or worse yet, use Reflection methods to try and parse the constants from the class. As of 5.3, it's very easy to do the following:

<?php

class Cow
{
    const 
NAME 'Herbert';
}

$cow 'Cow';
print 
$cow::NAME;

Toggle plain-text

Namespaces

PHP has long needed support for namespaces, and even though the new implementation is a little weird, it is certainly better than nothing (for most of us). At first, I was a little put-off by the Backslash delimiter (\) used for namespaces, as it is a departure form the C-like syntax that PHP usually honors. After a few uses, however, I found the PHP implementation quite easy to use, and could really care less whether it irks the C zealots who already hate PHP for a million other reasons besides this one.

The following code sample contains some different examples to try out:

<?php

namespace Work;

class 
Computer
{
    public static function 
power()
    {
        print 
"Boo. I don't want to work now.\n";
    }
}

namespace 
Play;
class 
Computer
{
    public static function 
power()
    {
        print 
"All right! Video games!\n";
    }
}

//using sub namespace
namespace Work\Exciting;
class 
Computer
{
    public static function 
power()
    {
        print 
"This Job Rocks!\n";
    }
}

//Sample Usage Method #1
namespace Work;
Computer::power();

namespace 
Play;
Computer::power();

namespace 
Work\Exciting;
Computer::power();

//Sample Usage Method #2
\Work\Computer::power();

\Play\Computer::power();

\Work\Exciting\Computer::power();

Toggle plain-text

In a real-world implementation, I would caution against placing multiple namespaces in the same file, but if you absolutely had to, you could use the bracket method to declare your namespaces in addition to methods outlined above. This only works if you place your namespaces in a separate file, with no additional code among them. Consider the following:

<?php

//another way to declare namespaces when using multiple namespaces in a file
namespace BracketSyntax
{
    class 
Computer
    
{
        public static function 
power()
        {
            print 
"I am in a different file!\n";
        }
    }
}

namespace 
BracketSyntax2
{
    class 
Computer
    
{
        public static function 
power()
        {
            print 
"I am in a different file too!\n";
        }
    }
}

Toggle plain-text

If you placed the above code in a file named bracketed_ns.php, you could call the appropriate classes in the same fashion as the previous examples:

<?php

//Method #3
require('bracketed_ns.php');
\BracketSyntax\Computer::power();
\BracketSyntax2\Computer::power();

Toggle plain-text

If you are interested in checking out additional changes in version 5.3, head on over to the php.net release announcement page for a full list of new features.

Suggested Reading

Essential PHP Security

by Chris Shifflet

Essential PHP Security is the one-stop PHP security handbook. PHP security Guru, Chis Shifflet, provides the reader with all the steps necessary to bolster the security of any web application. This book does a great job of breaking common security pitfalls into easy-to-digest explanations that will provide insight to any PHP coder, novice to expert. This is a must-have for web application developers. Don't leave home without it!

Suggested Reading

PHP Design Patterns

by Aaron Saray

Seasoned programmers looking for a good book on PHP design patterns will thoroughly enjoy PHP Design Patterns. Weighing in under 250 pages of readable content, it presents a truckload of philosophy and pattern samples in a well-condensed format, with short, consistent chapters. The title starts off with a quick explanation of patterns, champions their usage, and by chapter 3, the user is thrust right into the Adapter Pattern. For the next seventeen chapters, the user is given a synopsis, a problem/solution summary, a UML diagram, and code examples for each of the patterns in the discussed in the book. Generally, the code provides a typical approach, and then a modified approach using the chapter's pattern.

Suggested Reading

PHP Objects, Patterns, and Practice

by Matt Zandstra

Apress' PHP Objects, Patterns, and Practice is great for beginners and veterans alike. The first several chapters focus entirely on the foundations of Object-Oriented PHP (OOPhp), while later chapters teach various patterns such as the Factory, Singleton, Observer, and more. The author, Matt Zandstra, places major emphasis on good programming habits and strives to teach as many enterprise level practices as space allows. The last chapters introduce the reader to a series of productivity tools which cover version control, documentation, automated builds, and unit testing. This text will complement any OOPhp application developer, and I recommend it to anyone looking to dive in, or a seasoned OOPhp developer looking to pick up some new tricks and tools.

Suggested Reading

PHP 6 and MySQL 5

by Larry Ullman

I keep a copy of Visual Quickpro Guide, PHP 6 and MySQL 5 on my shelf to loan out to new PHP developers that have done little more than dabble in PHP for their personal website, and so on. I literally wore an older edition of this book out by reading it from cover-to-cover, re-reading it, and carrying it around with me everywhere I went. It was like my first guitar, I used the heck out of it! As the name implies, this book is designed to get you going. Larry Ullman does a great job of teaching the basics so that you can get a dynamyic website talking to a MySQL database, complete with forms, sessions, cookies, security mechanisms, and on and on...If you don't know PHP, but are looking for a great way to dive in, buy this book.

Tags: php 5.3, static, method, namespaces
Short URL: http://sqb.in/s2tq