Late Static Binding

Something that tends to come up when people are talking about new features in php 5.3 is late static binding. It sounds kind of impressive but there isn’t really a lot to it on a high level. In short, late static binding deals with dynamically scoping self referential static variables and methods.

First step is understanding what a static method/class is actually is. The short, only-what-you-need, explanation is that a static method/class is defined at compile time. Its made once and set in stone similarly to constants. Hopefully you’ve run across statics before, but what ‘compile time’ implicates should become a bit more clear as we go along.

Since the method is scoped during compile time this makes the question of propery and method inheritance a little tricky.

For example:

1
2
3
4
class theParent {
public static function test() {
self::output();
}
1
<code lang="php">

public static function output() {
return ‘The parent wins’;
}
}

1
<code lang="php">

class theChild extends theParent {
public static function output() {
return ‘The child wins’;
}
}

1
 
1
    echo theChild::test();

The problem is what theChild class should echo.

The usual OOP answer would be “The child wins”, but that only works because the self reference variable in instance/virtual objects is bound dynamically, the method is filled out at run time to the child scope. Run-time gives us the luxury of being able to consider where something came from and provide dynamic scoping. This is called ‘late’ binding.

Since statics are determined at compile time, however, the compiler needs to determine where self:: points to. What the compiler does can differ, it can bake theParent into theChild or, as quite a few languages do, it can keep the classes separate with only 1 actual definition of test() in the parent. So, since it is only built once, it is built with self pointing to the parent. Our example will actually give us “The Parent Wins”. This is known as ‘early binding’.

So, in php anyway, late (or lazy) static binding is introduced with the ‘static’ keyword.

1
2
3
4
class theParent {
public static function test() {
static::output();
}
1
<code lang="php">

public static function output() {
return ‘The parent wins’;
}
}

1
<code lang="php">

class theChild extends theParent {
public static function output() {
return ‘The child wins’;
}
}

1
 
1
    echo theChild::test();

Will return ‘The child wins’ as we would expect from usual object oriented code. This makes it possible to use statics in a more OOP way where you can actually call the parent separately from the child. Whether or not this means its ok to use statics in OOP code is debatable however since statics still cause problems with coupling and encapsulation and therefore testing and can be easily misused.

Leave a Reply

Your email address will not be published. Required fields are marked *