sweet idleness

T_PAAMAYIM_NEKUDOTAYIM

December 18, 2009

PHP supports the concept of variable functions. Append parentheses to a variable and the function with the same name as whatever the variable evaluates to will be executed.

$func = ‘this_is_a_php_func’;
$func();

In the example above,  $func() will be evaluated as this_is_a_php_func().

Variable functions can even be used to access class methods.

class Bar {
  function __construct(){
    print “Bar::__constructor()”;
  }

  static function test ($param1, $param2){
    print “Bar::__constructor()\n”;
    print “Bar::param1 : ” . $param1 .”\n”;
    print “Bar::param2 : ” . $param2 .”\n”;
  }
 
  function test2 ($param1, $param2){
    print “Bar::__constructor()\n”;
    print “Bar::param1 : ” . $param1 .”\n”;
    print “Bar::param2 : ” . $param2 .”\n”;
  }
}

// access method test
$func = ‘test’;
$bar = new Bar();
$bar->$func(’aaa’,'bbbb’);

// access static method test2
$func = ‘test2′;
Bar::$func(’aaa’, ‘bbbb’);

It works for functions, will it work for class names too?

$class = “Bar”;
$func = “test2″;
$class::$func(’aaa’,'bbb’);

Unfortunately, the answer to my question was a syntax error which I initially mistook as a message from The Great Omniscient One asking me to repent. 

I looked up the Hebrew for repent.

It wasn’t  PHP Parse error:  syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM.

Bummer.

The following, however, does work quite well.

call_user_func(array($class, $func), ‘aaa’,'bbb’)

Posted by george at 5:16 pm | permalink

Previous Comments

It really a useful idea.I will have a tiral of this idea as soon as possible as have already frustrated by them for a long time.Thank you very much for your continously post of effective tips.

Posted by supra shoes at January 6, 2011, 9:08 am

I should remember your pleasures with gratitude, as i would the harvest of a good time.

Posted by Fox Hats at March 30, 2011, 8:46 am