Extremist Developer

RSS

php: static call on non-static function

Somebody asked on the php Google Group on how to make a static call on a non-static function. (don’t ask me why) Here is my (very nasty) solution :

<?php
abstract class SomeClass
{   
   protected function test() {
      echo "test 42";
   }
}
 
class AnotherClass extends SomeClass {
 
   private static $_instance = null;
 
   public static function __callStatic($name, $args) {
      if(is_null($_instance)) {
         self::$_instance = new __CLASS__;
      }
      if(method_exists(self::$_instance, $name)) {
         call_user_func_array(array(self::$_instance, $name), $args);
      }
   }
 
   public function test() {
      parent::test();
      return " 43";
   }
}
 
echo AnotherClass::test();
//outout test 42 43

Basically, we use the magic method __callStatic, and we create a Singleton instance of our object to take care of any static call on a non-static function. Might not work for all the cases, but does the job. And again, it’s nasty.

The discussion: http://groups.google.com/group/comp.lang.php/browse_thread/thread/28a76ab2c35f7493#

p.s.: Tumblr, please add Code highlighting