If the anonymous function has access only to public elements, whether they are attributes or methods of the class, the code is basically what Guilherme described in the comments: a static method that creates a new instance of the class and passes it as a parameter to the class. anonymous function. That simple. Here's an example:
class Groot {
private function __construct() {
$this->name = "I'm groot!";
}
public function getName() {
return $this->name;
}
public static function create($callback) {
// Cria uma nova instância da classe:
$new = new self();
// Invoca a função anônima passando a instância como parâmetro:
$callback($new);
}
}
Groot::create(function ($self) {
echo $self->getName(), PHP_EOL;
});
Get up and running at Ideone | Repl.it
For the anonymous role to have access to the private elements, you need to associate the function with the object with Closure::bind
. Here's an example:
class Groot {
private $name;
private function __construct() {
$this->name = "I'm groot!";
}
public function getName() {
return $this->name;
}
public static function create($callback) {
// Cria uma nova instância da classe:
$new = new self();
// Associa a função ao objeto:
$callback = Closure::bind($callback, null, $new);
// Invoca a função anônima passando a instância como parâmetro:
$callback($new);
}
}
Groot::create(function ($self) {
echo $self->name, PHP_EOL;
});
See working in Ideone | Repl.it
Even $name
being a private attribute, the anonymous function will have access to it.