Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an object method as a callback function

Tags:

php

I have the below method in a singleton class

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 '';
    }
}

this works fine as an ordinary function

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 '';
    }
}

when using inside a class i'm getting the below error:

PHP Warning: array_map(): The first argument, '$this->rfc_encode', should be either NULL or a valid callback

Please could anybody help me to fix this.

like image 651
Karthik Avatar asked Jul 28 '10 07:07

Karthik


People also ask

Is a callback function an object?

Simply put: A callback is a function that is to be executed after another function has finished executing — hence the name 'call back'. More complexly put: In JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions.

How do you write a callback function in Objective C?

Show activity on this post. @interface Robot: NSObject + (void)sayHi:(void(^)(NSString *))callback; @end @implementation Robot + (void)sayHi:(void(^)(NSString *))callback { // Return a message to the callback callback(@"Hello to you too!"); } @end [Robot sayHi:^(NSString *reply){ NSLog(@"%@", reply); }];

How do you write a callback function?

A custom callback function can be created by using the callback keyword as the last parameter. It can then be invoked by calling the callback() function at the end of the function. The typeof operator is optionally used to check if the argument passed is actually a function. console.


1 Answers

From PHP Manual on Callbacks:

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

So try

return array_map(array($this, 'encode'), $inp);
like image 87
Gordon Avatar answered Sep 22 '22 14:09

Gordon