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?

5
  • What's your PHP version? Commented Sep 4, 2013 at 16:54
  • 2
    Use anonymous functions: array_filter(..., function($var) { ... }); (Sorry, didn't really understand the problem first.) Commented Sep 4, 2013 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? Commented Sep 4, 2013 at 16:58
  • The "nested" function ends up in the global scope; you can't use $this inside of it. Commented Sep 4, 2013 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? Commented Jun 23, 2020 at 9:57

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

1

One solution is to use anonymous functions:

$aids = implode(';', array_filter(explode(';', $aids), function($var) { return $this->attachment_owner($var, $user_id); }));

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.