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';
});

もちろん、次のエラーが表示されます。

致命的なエラー: オブジェクト コンテキストでない場合に $this を使用する

私の質問は、コールバック関数内を使用してこの動作を実現する方法があるかどうか、$thisまたはより良いパターンの提案を得る方法があるかどうかです。

PS: コールバックを使用することを好みます。

4

2 に答える 2

6

PHP 5.4 を使用している (またはアップグレードする予定がある) 場合は、ClosuresbindToの新しい方法を使用できます。これにより、クロージャーを新しいスコープに「再バインド」できます。

を呼び出す前$callbackに、必要に応じて設定でき$thisます。

if(is_callable($callback)){
    $callback = $callback->bindTo($this, $this);
    $callback();
}

デモ: http://codepad.viper-7.com/lRWHTn

bindTo授業以外でもご利用いただけます。

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

デモ: http://codepad.viper-7.com/mNgMDz

于 2012-05-18T18:08:51.387 に答える
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;
  }
}

そして、コールバックを宣言し、次のように使用します。

$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');
});


の直後に次のコード行を呼び出します。

var_dump($myObject);

これを出力します:

object(myObject)[1]
  protected 'property' => string 'value' (length=5)
  protected 'anotherProperty' => string 'anotherValue' (length=12)

これは、コールバックが実行され、オブジェクトのプロパティが実際に設定されていることを示しています。

于 2012-05-18T17:56:45.300 に答える