我正在使用匿名函数,我在对象外部创建匿名函数,然后将其添加到稍后将与 __callStatic 魔术函数一起使用的对象。添加的闭包包含来自父类的方法。我想知道我是否能够从闭包中调用这些方法?
现在我收到这个错误:
EmptyObject::addMethod('open', function(){
if (static::_hasAdapter(get_class(), __FUNCTION__))
return self::_callAdapter(get_class(), __FUNCTION__, $details);
echo '<p>You have mail!</p>';
});
抛出这个错误:
Fatal error: Cannot access static:: when no class scope is active in
和
//Add the functions
EmptyObject::addMethod('open', function(){
if (EmptyObject::_hasAdapter('EmptyObject', __FUNCTION__))
return EmptyObject::_callAdapter('EmptyObject', __FUNCTION__, $details);
echo '<p>You have mail!</p>';
});
抛出这个错误是因为方法被保护了
Fatal error: Uncaught exception 'BadMethodCallException' with message 'Method '_hasAdapter' was not found in class EmptyObject'
最佳答案
您可以使用 Closure::bind() 来实现此目的(PHP >= 5.4.0)
abstract class EmptyObject
{
protected static $methods = array();
final public static function __callStatic($name, $arguments)
{
return call_user_func(self::$methods[$name], $arguments);
}
final public static function addMethod($name, $fn)
{
self::$methods[$name] = Closure::bind($fn, NULL, __CLASS__);
}
final protected static function protectedMethod()
{
echo __METHOD__ . " was called" . PHP_EOL;
}
}
现在任何传递给 EmptyObject::addMethod() 的匿名函数都将在 EmptyObject 类的范围内运行
EmptyObject::addMethod("test", function()
{
self::protectedMethod();
});
// will output:
// EmptyObject::protectedMethod was called
EmptyObject::test();
关于php - 匿名函数/闭包和使用 self::or static::,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8287390/