R
R
Roman Basharin2017-08-18 23:18:55
PHP
Roman Basharin, 2017-08-18 23:18:55

Why can't you pass a property of the current object to a closure?

Greetings colleagues. Help to understand the intricacies of the language. The second hour I can not find anything even close similar. The manual from SO has already subtracted everything)) The error is as follows:
PHP Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR), expecting ')', Apparently in this place $this -> db
Code:

class Orders {
  function __construct(Database $db) {
    $this->db = $db;
  }

  function createOrder(array $data) {
    $this->db->transaction(function($this->db) { // ошибка в этой строке
      $id1 = $this->db->insert('...');
      $id2 = $this->db->insert('...');
      $res = $this->db->update('...');
    });
  }
}
$orders = new Orders($db);


function createOrder(array $data) {
  $db = $this->db;
  $this->db->transaction(function($db) { // Так работает
  $this->db->transaction(function() use ($db) { // И так тоже
    $id1 = $this->db->insert('...');
    $id2 = $this->db->insert('...');
    $res = $this->db->update('...');
  });
}

It's not convenient at all, in each method to drive into the local variable $db = $this->db, now there are 5 of them, and when there will be 25, it's kabzda.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav B, 2017-08-18
@Hellek

Since PHP 5.4 you have $this available inside an anonymous function declared inside a class.
you don't have to send anything there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question