如何使用对象方法作为回调函数

Kaa*_*rtz 11 php

我在单例类中有以下方法

private function encode($inp)
{
    if (is_array($inp) {
        return array_map('$this->encode', $inp);
    } else if is_scalar($inp) {
        return str_replace('%7E', rawurlencode($inp));
    } else {
        return '';
    }
}
Run Code Online (Sandbox Code Playgroud)

这作为一个普通的功能很好

function encode($inp)
{
    if (is_array($inp) {
        return array_map('encode', $inp);
    } else if is_scalar($inp) {
        return str_replace('%7E', rawurlencode($inp));
    } else {
        return '';
    }
}
Run Code Online (Sandbox Code Playgroud)

当在一个类中使用时,我得到以下错误:

PHP警告:array_map():第一个参数'$ this-> rfc_encode'应该是NULL或有效的回调

请任何人帮我解决这个问题.

Gor*_*don 22

来自PHP回调手册:

实例化对象的方法作为包含索引0处的对象和索引1处的方法名称的数组传递.

所以试试吧

return array_map(array($this, 'encode'), $inp);
Run Code Online (Sandbox Code Playgroud)

  • 此外,方法`encode`必须是[public](http://php.net/manual/en/language.oop5.visibility.php). (7认同)