How can I use a callback function which is stored as a class member in PHP?

Consider the following code, which is a scheme of storing a callback function as a member, and then using it:

class MyClass {
  function __construct($callback) {
    $this->callback = $callback;
  }

  function makeCall() {
    return $this->callback();
  }
}

function myFunc() {
  return 'myFunc was here';
}

$o = new MyClass(myFunc);
echo $o->makeCall();

I would expect myFunc was here to be echoed, but instead I get:

Call to undefined method MyClass::callback()

Can anyone explain what's wrong here, and what I can do in order to get the desired behaviour?

In case it matters, I am using PHP 5.3.13.


您可以将您的makeCall方法更改为:

function makeCall() {
  $func = $this->callback; 
  return $func();
}

将其作为字符串传递并通过call_user_func调用它。

class MyClass {
  function __construct($callback) {
    $this->callback = $callback;
  }

  function makeCall() {
    return call_user_func($this->callback);
  }
}

function myFunc() {
  return 'myFunc was here';
}

$o = new MyClass("myFunc");
echo $o->makeCall();

One important thing about PHP is that it recognises the type of a symbol with the syntax rather than the contents of it, so you need to state explicitly what you refer to.
In many languages you just write:

myVariable
myFunction
myConstant
myClass
myClass.myStaticMethod
myObject.myMethod

And the parser/compiler knows what each of the symbols means, because it's aware of what they refer to simply by knowing what's assigned to them.
In PHP, however, you need to use the syntax to let the parser know what "symbol namespace" you refer to, so normally you write:

$myVariable
myFunction()
myConstant
new myClass
myClass::myStaticMethod()
$myObject->method()

However, as you can see these are calls rather than references. To pass a reference to a function, class or method in PHP, combined string and array syntax is used:

'myFunction'
array('myClass', 'myStaticMethod')
array($myObject, 'myMethod')

In your case, you need to use 'myFunc' in place of myFunc to let PHP know that you're passing a reference to a function and not retrieving the value the myFunc constant.

Another ramification is that when you write $myObject->callback(), PHP assumes callback is a method because of the parentheses and it does not attempt to loop up a property .
To achieve the expected result, you need to either store a copy of/reference to the property callback in a local variable and use the following syntax:

$callback = $this->callback;
return $callback();

which identifies it as a closure, because of the dollar sign and the parentheses; or call it with the call_user_func function:

call_user_func($this->callback);

which, on the other hand, is a built-in function that expects callback.

链接地址: http://www.djcxy.com/p/57940.html

上一篇: 更多关于PHP OOP

下一篇: 我如何使用在PHP中作为类成员存储的回调函数?