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 ?

2
  • Why aren't you using prepared statements? Commented Apr 17, 2013 at 4:35
  • Please read my previous question, prepared statements did not apply to that case. Commented Apr 17, 2013 at 6:47

1 Answer 1

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
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.