PHP嵌套函数给出';不在对象上下文中使用$this';错误

PHP嵌套函数给出';不在对象上下文中使用$this';错误,php,Php,我正在尝试使用内置的array\u filter功能过滤数组。根据PHP手册中的示例,我必须提供回调函数的名称。下面是我尝试的: // 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) {

我正在尝试使用内置的
array\u filter
功能过滤数组。根据PHP手册中的示例,我必须提供回调函数的名称。下面是我尝试的:

// 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'));
}
下面是我得到的错误:

致命错误:在文件名行号中不在对象上下文中时使用$this


如何解决这个问题?

通过使嵌套函数成为类的成员,可以避免使用它

... 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')));
... 
参考资料:


通过使嵌套函数成为类的成员,可以避免使用该函数

... 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')));
... 
参考资料:


一种解决方案是使用匿名函数:

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

一种解决方案是使用匿名函数:

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

由于您使用的是PHP>5.4.0,因此可以创建一个甚至使用$this:


尽管如此,我还是会选择tim的解决方案,因为它更干净。

因为您使用的是PHP>5.4.0,所以您可以创建一个甚至使用$this:


尽管如此,我还是会选择tim的解决方案,因为它更干净。

您的PHP版本是什么?使用匿名函数:array_filter(…,function($var){…});(很抱歉,首先没有真正理解问题。)$这不再在范围内。出于好奇,为什么要在这里创建嵌套函数而不仅仅是类中的私有函数?嵌套函数最终位于全局范围内;你不能在它里面使用
$this
。我也有类似的问题,但我不能让它匿名,因为它被多次使用。我不希望它成为一种方法,因为它只与一种特定的方法相关。有什么想法吗?你的PHP版本是什么?使用匿名函数:array_filter(…,function($var){…});(很抱歉,首先没有真正理解问题。)$这不再在范围内。出于好奇,为什么要在这里创建嵌套函数而不仅仅是类中的私有函数?嵌套函数最终位于全局范围内;你不能在它里面使用
$this
。我也有类似的问题,但我不能让它匿名,因为它被多次使用。我不希望它成为一种方法,因为它只与一种特定的方法相关。有什么想法吗?