1

I am trying to filter an array using the built-in array_filter function. According to the examples in PHP manual, I have to provide the name of the callback function. So, here is what I tried:

// This function is a method 
public function send($user_id, $access, $content, $aids)
{
    // check if user is allowed to see the attachments
    function is_owner($var)
    {
        return $this->attachment_owner($var, $user_id);
    }

    $aids = implode(';', array_filter(explode(';', $aids), 'is_owner'));
}

Here is the error I'm getting:

Fatal error: Using $this when not in object context in filename line number.

How to solve this?

vaultah
  • 44,105
  • 12
  • 114
  • 143
  • What's your PHP version? – deceze Sep 04 '13 at 16:54
  • 2
    Use anonymous functions: array_filter(..., function($var) { ... }); (Sorry, didn't really understand the problem first.) – Niko Hujanen Sep 04 '13 at 16:56
  • $this is no longer within scope. Out of curiosity, why make a nested function here and not just a private function in the class? – Kai Qing Sep 04 '13 at 16:58
  • The "nested" function ends up in the global scope; you can't use `$this` inside of it. – lafor Sep 04 '13 at 16:59
  • i have similar issue, but i can't make it anonymous because it is used many times. and i don't want it to be a method because it's only relevant to one specific method. any ideas? – oriadam Jun 23 '20 at 09:57

3 Answers3

3

You could avoid using the nested function by making it a member of your class

... inside a class
function is_owner($var)
{
    return $this->attachment_owner($var, $user_id);
}

public function send($user_id, $access, $content, $aids)
{
// check if user is allowed to see the attachments


$aids = implode(';', array_filter(explode(';', $aids), array($this, 'is_owner')));
... 

References:

What are nested functions for

Array_filter in the context of an object, with private callback

Community
  • 1
  • 1
tim
  • 3,191
  • 2
  • 15
  • 17
2

Since you're using PHP > 5.4.0, you could create an anonymous function and even use $this:

public function send($user_id, $access, $content, $aids)
{   
    // check if user is allowed to see the attachments
    $is_owner = function ($var)
    {
        return $this->attachment_owner($var, $user_id);
    }
    $aids = implode(';', array_filter(explode(';', $aids), $is_owner));

Nevertheless I would go with tim's solution because it is cleaner.

ComFreek
  • 29,044
  • 18
  • 104
  • 156
1

One solution is to use anonymous functions:

$aids = implode(';', array_filter(explode(';', $aids), function($var) { return $this->attachment_owner($var, $user_id); }));
Niko Hujanen
  • 743
  • 5
  • 10