How to access objects of a class within an anonymous method?

1

I researched a lot on the internet but did not find how to develop, I will be very grateful for who can get me that doubt. I would like to develop a class in php where you could access your methods within an anonymous method as the example below:

MyClass::method('param1', function($class){
    $class->print('Hello World');
});

This example of usage I found in Laravel in your Mail class, example:

Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
    $m->from('[email protected]', 'Your Application');
    $m->to($user->email, $user->name)->subject('Your Reminder!');
});
    
asked by anonymous 03.10.2017 / 00:37

1 answer

1

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.

    
04.10.2017 / 22:54