In Javascript, I can bind this to another function and call it using .call or .apply
In PHP, I can do this with call_user_func or call_user_func_array , but how can I bind $this to a function?
JavaScript:
function greet() { alert('Hello ' + this.name); } function SomeClass() {} SomeClass.prototype = { name: 'John', test: function() { greet.call(this); } } var me = new SomeClass(); me.test();
PHP:
function greet() { echo 'Hello ' . $this->name; } class SomeClass { public $name = 'John'; function test() { call_user_func('greet'); } } $me = new SomeClass; $me->test();
UPDATE:
Thanks to @deceze for the idea of Reflection , I found these solutions, but I donβt think it is good for performance (x10 is slower than a direct call), but very clear when reading.
I wrote two functions:
// See also Javascript: Function.prototype.apply() function function_apply($fn, $thisArg, $argsArray = array()) { static $registry; if (is_string($fn)) { if (!isset($registry[$fn])) { $ref = new \ReflectionFunction($fn); $registry[$fn] = $ref->getClosure(); } $fn = $registry[$fn]; } return call_user_func_array($fn->bindTo($thisArg), $argsArray); } // See also Javascript: Function.prototype.call() function function_call($fn, $thisArg /*, arg1, arg2 ... */) { return function_apply($fn, $thisArg, array_slice(func_get_args(), 2)); }
and replace call_user_func with function_call :
function greet() { echo 'Hello ' . $this->name; } class SomeClass { public $name = 'John'; function test() { function_call('greet', $this); } } $me = new SomeClass; $me->test();
source share