Written by Gareth Rodger on November 30, 2008 – 3:29 pm
With the advent of PHP 5.3 just around the corner it’s time to start thinking how some of the new features will affect you.
In this post i’m going to focus on one of the smaller and more overlooked features, the improved static method/property access.
So to start let’s create a basic static class:
class product { public static $name; public static $colour; public static $price; public static function getColour() { $tmp_colour = 'The colour is: ' . self::$colour; return $tmp_colour; } }
To access the properties and methods of this class prior to PHP 5.3 we’d do the following:
// Prior to PHP 5.3 print product::$name; print product::$price; print product::getColour();
Now the beauty of the feature in PHP 5.3 is that you can abstract the name of the class when referencing the static methods and properties:
// PHP 5.3 $prod_class = 'product'; print $prod_class::$name; print $prod_class::$price; print $prod_class::getColour();
See the benefit yet? If you need to switch in a new class with a new name it’s a three line change in the first code segment due to the hardcoded class name, whereas in the second segment it’s a one line change.
Scale this to a larger project with multiple static classes and lot’s of calls and it’s a nice little bit of abstraction.
There’s more to come on the PHP 5.3 update in future posts so stay tuned!