Tuesday, January 6, 2009

Static Fields and Methods

One nice feature of PHP is its support for magic methods. These allow a class or object to catch a range of events such as method calls and property accesses. This kind of interception is really powerful and allows classes to implement all sorts of dynamic behaviour. For example, a database wrapper could intercept property access to get a property value from a database row. Many scripting languages offer something similar, for example Groovy has its own set of interceptors.

php.net is implemented in C and under the covers it implements magic methods by attaching a table of function pointers to each object (called the object handlers). In most cases the default implementation of an object handler is to simply call the appropriate PHP method on the class. 

For example, there is a __call object handler which calls the __call PHP magic method if it exists. Built in classes like SimpleXML and MySQLi use object handlers to implement whatever logic they need. All of this and a lot more besides is documented in Sara Golemans book.

In Project Zero we added magic methods like __call, __get and __set a long time ago. Over the Christmas break we finally got round to adding their static equivalents: __callStatic, __getStatic, __setStatic and __issetStatic

Here's an example of how __callStatic can be used:


class Foo {
  static public function __callStatic($a, $b) {
  print "__callStatic [$a]\n";



We have also surfaced this feature into the Java Bridge:


java_import("java.lang.Integer", NULL, FALSE);


// Signatures also work as normal!
$signature = new JavaSignature(JAVA_STRING);
var_dump(Integer::parseInt($signature, "1234567890"));


This makes for a much cleaner syntax than using JavaClass. JavaClass was always something of an anomaly (er, hack) as it required the script to create an instance of an object just to access static class methods and properties. 

More information about this feature will be available just as soon as the Project Zero documentation has rebuilt tonight [:o)

No comments:

Post a Comment