References to class members in PHP
Posted in Examples, php code on August 27th, 2010 by sinica – Be the first to comment Tags: code share, phpWe have decided to switch the server-side of Quark Framework 2.0 to the php language. The main reason is that PHP is everywhere,many programmers (and even non programmers) can deal with it and we can be more agile with PHP than with java. Also the hosting costs for SaaS are lower with PHP. I did programming for more then 14 years in strongly typed languages like C,C++,Java,C#,Action Script and I hate that I don’t have types for parameters in php and I don’t like how strange is PHP occasionally (php references are unlike others in any decent language I’ve ever used, the insane and ugly $this-> is annoying etc ). I’m not a big fan of Php but for what we need it is a rational choice (Don’t forget the unit tests or you are doooomed
)
Anyway,PHP is serving us well and I’ve decided to share here a small php class that will act like a sort of reference to function members. A closure could solve sometimes the same problem (sort of) but it will not make the code clearer. And it will not work for calling members from another class/instance.
class FunctionRef
{
protected $mythis;
protected $myFunction;
public function __construct($mythis,$myFunction)
{
$this->mythis = $mythis;
$this->myFunction = $myFunction;
}
public function call()
{
$args = func_get_args();
call_user_func_array(array(&$this->mythis, $this->myFunction), $args);
}
}
If you know a better way on doing this in PHP, I will be glad to know.
