In Javascript, i this
an eine andere Funktion binden kann, und rufen Sie es mit .call
oder .apply
PHP call_user_func binden thisArg wie Call Javascript
In PHP, ich kann das tun mit call_user_func
oder call_user_func_array
, aber wie kann ich $this
binden in die Funktion?
Javascript:
function greet() {
alert('Hello ' + this.name);
}
function SomeClass() {}
SomeClass.prototype = {
name: 'John',
test: function() {
greet.call(this);
}
}
var me = new SomeClass();
me.test(); // Hello John
PHP:
function greet() {
echo 'Hello ' . $this->name;
}
class SomeClass {
public $name = 'John';
function test() {
call_user_func('greet');
}
}
$me = new SomeClass;
$me->test(); // Fatal error: Using $this when not in object context
UPDATE:
Danke für die Reflection
Idee @deceze, habe ich diese Lösungen gefunden, aber ich glaube nicht, es ist gut, für die Leistung (x10 langsamer als direkt anrufen), aber viel klar beim Lesen.
Ich habe schreibt zwei Funktionen:
// 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));
}
und ersetzen call_user_func
-function_call
:
function greet() {
echo 'Hello ' . $this->name;
}
class SomeClass {
public $name = 'John';
function test() {
function_call('greet', $this);
}
}
$me = new SomeClass;
$me->test(); // Hello John
Warum zur Folge haben Sie kein Argument für diese Funktion hinzufügen, und die Variable als Argument übergeben ? Sonst kann Ihnen das Schlüsselwort 'use' helfen. (http://php.net/functions.anonymous) Aber ich bin mir nicht wirklich sicher. –
Mögliches Duplikat von http://stackoverflow.com/questions/27014664/php-equivalent-of-avascript-bind – haim770
wie ich weiß, ist dies eine Lösung, die '$ this' als Argument übergeben, nur neugierig, gibt es irgendeine Möglichkeit, wie funktioniert Javascript – user1542316