在对象上下文中运行的回调函数?

mar*_*cio 3 php php-5.3

我试图在运行时配置一个对象传递一个回调函数,如下所示:

class myObject{
  protected $property;
  protected $anotherProperty;

  public function configure($callback){
    if(is_callable($callback)){
      $callback();
    }
  }
}

$myObject = new myObject(); //
$myObject->configure(function(){
  $this->property = 'value';
  $this->anotherProperty = 'anotherValue';
});
Run Code Online (Sandbox Code Playgroud)

当然我收到以下错误:

致命错误:在不在对象上下文中时使用$ this

我的问题是,如果有一种方法可以$this在回调函数内部使用或者可能获得更好模式的建议.

PS:我更喜欢使用回调.

Pas*_*TIN 6

从您的想法开始,您可以将$this参数作为参数传递给回调

但请注意,您的回调 (未在您的类中声明) 将无法访问受保护的属性/方法 - 这意味着您必须设置公共方法来访问它们.


你的课程看起来像这样:

class myObject {
  protected $property;
  protected $anotherProperty;
  public function configure($callback){
    if(is_callable($callback)){
      // Pass $this as a parameter to the callback
      $callback($this);
    }
  }
  public function setProperty($a) {
    $this->property = $a;
  }
  public function setAnotherProperty($a) {
    $this->anotherProperty = $a;
  }
}
Run Code Online (Sandbox Code Playgroud)

并且你已经宣布回调,并使用它,如下所示:

$myObject = new myObject(); //
$myObject->configure(function($obj) {
  // You cannot access protected/private properties or methods
  // => You have to use setters / getters
  $obj->setProperty('value');
  $obj->setAnotherProperty('anotherValue');
});
Run Code Online (Sandbox Code Playgroud)


紧接着之后调用以下代码行:

var_dump($myObject);
Run Code Online (Sandbox Code Playgroud)

输出这个:

object(myObject)[1]
  protected 'property' => string 'value' (length=5)
  protected 'anotherProperty' => string 'anotherValue' (length=12)
Run Code Online (Sandbox Code Playgroud)

这表明已经执行了回调,并且确实已经按预期设置了对象的属性.


Roc*_*mat 6

如果您正在使用(或者愿意升级到)PHP 5.4,那么您可以使用新bindTo闭包方法.这允许您将闭包"重新绑定"到新范围.

在通话之前$callback,您可以将其设置$this为您想要的.

if(is_callable($callback)){
    $callback = $callback->bindTo($this, $this);
    $callback();
}
Run Code Online (Sandbox Code Playgroud)

演示:http://codepad.viper-7.com/lRWHTn

你也可以bindTo在课外使用.

$func = function(){
  $this->property = 'value';
  $this->anotherProperty = 'anotherValue';
};
$myObject->configure($func->bindTo($myObject, $myObject));
Run Code Online (Sandbox Code Playgroud)

演示:http://codepad.viper-7.com/mNgMDz

  • +1这是将PHP升级到最新版本的另一个原因;-) (3认同)