1

Based on my previous question's answer , I have to use an inner function for array_map() as follow:

    $keyword_tokens = array_map(
        function($keyword) {
            return $this->db->escape_string(trim($keyword));
        }, $keyword_tokens
    );

$this->db is a MySQLi database wrapper, while its function escape_string() is a wrapper of mysqli_real_escape_string().

The problem is, PHP prompts error:

Fatal error: Using $this when not in object context

However, the array_map code piece is within a public function within a class. My question is: How can I reference $this->db in the array_map()'s inner function ?

Community
  • 1
  • 1
Raptor
  • 53,206
  • 45
  • 230
  • 366

1 Answers1

2

Use the use keyword to include variables in the closure's scope, though you'll have to use a different variable to $this if you're using a PHP version prior to 5.4. Perhaps this...

$db = $this->db;
$keyword_tokens = array_map(
    function($keyword) use ($db) {
        return $db->escape_string(trim($keyword));
    }, $keyword_tokens
);
Phil
  • 157,677
  • 23
  • 242
  • 245