I’m trying to configure an object at runtime passing a callback function like so:
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 when not in object context
My question is if there is a way to achieve this behavior using $this inside a callback function or maybe get a suggestion for a better pattern.
PS: I prefer to use a callback.
Starting with your idea, you could pass
$thisas a parameter to your callbackBut note that your callback (which is not declared inside your class) will not be able to access protected nor private properties/methods — which means you’ll have to set up public methods to access those.
Your class would then look like this :
And you’d declared you callback, and use it, like this :
Calling the following line of code just after :
Would output this :
Which shows that the callback has been executed, and the properties of your object have indeed been set, as expected.