php goodness

Late static binding before PHP 5.3

Posted in Short by phpgoodness on July 20, 2010

If you are still lazy (or funk) to upgrade to PHP 5.3 and use the numerous cool new features, or your hands are simply tied because of those nasty backwards compatibility issues, here’s a little trick how to emulate late static binding (or why don’t we call it static dynamic binding).

Let’s start with class constants. Feel free to use this piece of code to access child class constants from the parent:

constant( get_class( $this ) . '::CONSTANT_NAME' );

For static methods:

call_user_func( array( get_class( $this ), 'method_name' ), 'param1' );

And (eeh) for variables:

eval( 'return ' . get_class( $this ) . '::$variable;' );

Finally, putting this all together in one horrible example:

class A
	function  __construct()
			array( get_class( $this ), 'echoHello' ),
			constant( get_class( $this ) . '::SAYING_HELLO' ),
			eval( 'return ' . get_class( $this ) . '::$name;' )
class B extends A
	const SAYING_HELLO = 'Hi';
	static $name = 'Mr. Buzz Killington';
	static function echoHello( $saying_hello, $name )
		echo "$saying_hello $name";
$b = new B;

What’s the problem here? There are 3 issues why you still have to do that damn upgrade.

  1. Ugly.
  2. Performance; this is simply slow.
  3. This is not real late static binding. In real late static binding you will execute the method that is defined in the latest derived class where the static method is defined. In our case, this class is always the currently executing, final class (the class of $this), so we don’t really talk about inheritance here.To hack “real” static binding, you should iterate through the parents one by one of the class of $this in case the method (or variable or constant) is not defined.

Conclusions? If you really need late static binding, you’d better upgrade, or simply don’t use static methods variables and class constants.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: