Does the callback function work inside the context of an object?

I am trying to set up an object at runtime by passing a callback function as follows:

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

Of course, I get the following error:

Fatal error: using $ this if not in object context

My question is, is there a way to achieve this behavior using $thisthe callback functions inside, or perhaps get an offer for a better template.

PS: I prefer to use a callback.

+3
source share
2 answers

Starting with your idea, you can pass $thisas a parameter to the callback

, ( ) / - , .


:

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)

, , , .

+6

( ) PHP 5.4, bindTo . " " .

$callback $this , .

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

DEMO: http://codepad.viper-7.com/lRWHTn

bindTo .

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

DEMO: http://codepad.viper-7.com/mNgMDz

+6

All Articles