Assign a static function to a variable in PHP

Posted by Felipe Almeida on Stack Overflow See other posts from Stack Overflow or by Felipe Almeida
Published on 2012-09-26T03:31:50Z Indexed on 2012/09/26 3:37 UTC
Read the original article Hit count: 136

Filed under:
|
|

I would like to assign a static function to a variable so that I can send it around as a parameter. For example:

class Foo{
    private static function privateStaticFunction($arg1,$arg2){
      //compute stuff on the args          
    }

    public static function publicStaticFunction($foo,$bar){

         //works
         $var = function(){
                   //do stuff
                };

         //also works
         $var = function($someArg,$someArg2){
                   //do stuff
         };

         //Fatal error: Undefined class constant 'privateStaticFunction'                    
         $var = self::privateStaticMethod;

         //same error
         $var = Foo::privateStaticFunction;

         //compiles, but errors when I try to run $var() somewhere else, as expected
         //Fatal error: Call to private method Foo::privateStaticMethod() from context ''
         $var = function(){
             return Foo::privateStaticMethod(); 
         }; 
    }
}

I've tried a few more variations but none of them worked.

I don't even expect this sort of functional hacking to work with PHP but hey, who knows?

Is it possible to do that in PHP or will I need to come up with some hack using eval?

P.S.: LawnGnome on ##php mentioned something about it being possible to do what I want using array('Foo','privateStaticMethod') but I didn't understand what he meant and I didn't press him further as he looked busy.

© Stack Overflow or respective owner

Related posts about php

Related posts about php5