How to Use a Class Method as a Callback Function

How to use class methods as callbacks

Check the callable manual to see all the different ways to pass a function as a callback. I copied that manual here and added some examples of each approach based on your scenario.

Callable


  • A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo, empty(), eval(), exit(), isset(), list(), print or unset().
  // Not applicable in your scenario
$this->processSomething('some_global_php_function');

  • A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.
  // Only from inside the same class
$this->processSomething([$this, 'myCallback']);
$this->processSomething([$this, 'myStaticCallback']);
// From either inside or outside the same class
$myObject->processSomething([new MyClass(), 'myCallback']);
$myObject->processSomething([new MyClass(), 'myStaticCallback']);

  • Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0.
  // Only from inside the same class
$this->processSomething([__CLASS__, 'myStaticCallback']);
// From either inside or outside the same class
$myObject->processSomething(['\Namespace\MyClass', 'myStaticCallback']);
$myObject->processSomething(['\Namespace\MyClass::myStaticCallback']); // PHP 5.2.3+
$myObject->processSomething([MyClass::class, 'myStaticCallback']); // PHP 5.5.0+

  • Apart from common user-defined function, anonymous functions can also be passed to a callback parameter.
  // Not applicable in your scenario unless you modify the structure
$this->processSomething(function() {
// process something directly here...
});

How can I pass a class member function as a callback?

That doesn't work because a member function pointer cannot be handled like a normal function pointer, because it expects a "this" object argument.

Instead you can pass a static member function as follows, which are like normal non-member functions in this regard:

m_cRedundencyManager->Init(&CLoggersInfra::Callback, this);

The function can be defined as follows

static void Callback(int other_arg, void * this_pointer) {
CLoggersInfra * self = static_cast<CLoggersInfra*>(this_pointer);
self->RedundencyManagerCallBack(other_arg);
}

ES6: How to call a class function from a callback function

function changes the meaning of this. One way to fix the problem is to use bind. However, you'd have to use it twice, because you have two layers of function. A simple way to solve it is to use arrow functions, which do not change this:

class MyClass {
constructor() {
this.a = '';
}

init() {
....
$.getJSON(url, (data) => {
$(mySelector).click(() => {
this.classFn();
});
});
}

classFn() {
....
}
}

How do I use a class method as a callback function?

If you want to specify a class method as a callback, you need to specify the object it belongs to:

array_walk($fieldsArray, array($this, 'test_print'));

From the manual:

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

How to use a callback function in a class with inheritance

Found a way to do the same thing but with a none static method

ES6 style allows you to use new features, such as super keyword. super keyword it's all about parent class context, when you are using ES6 classes syntax.

class Parent {
numbers: number[];

constructor(numbers: number[]) {
this.numbers = numbers;
}

protected iterateNumbers(predictionCallback: (nb: number) => void): void {
for (const nb of this.numbers) {
predictionCallback(nb);
}
}

protected inc(nb: number): number {
return nb++;
}
}

class Child extends Parent {

constructor(numbers: number[]) {
super(numbers)
}

getNumbers() {
this.iterateNumbers(this.displayNumber);
}

private displayNumber(nb: number): void {
console.log(super.inc(nb));
}
}

const c = new Child([1, 2, 3, 4, 5]);
c.getNumbers();

Passing class method as callback to another class in javascript

I changed the foo and bar to Form and Popup:

1) Quick — and possibly dirty — solution:

You can send this as the second argument to .fire():

class Form {
constructor() {
this.property = 'yes';
}

eventMethod() {
let popup = new Popup();
popup.fire(this.endMethod, this);
}

endMethod(values, that) {
console.log(values + that.property);
}
}

class Popup {
constructor() {
this.property = 'no';
}

fire(callback, that) {
let value = 'message';
callback(value, that);
}
}

let form = new Form();
form.eventMethod();

How to call a class method as a callback function in wordpress custom endpoint?

If the hook is called within the class if-self and yout callback method is defined there:

add_action( 'rest_api_init', function () {
register_rest_route( 't2mchat/v2', '/get_curr_user_lang', array(
'methods' => 'GET',
'callback' => array($this,'get_user_lang')
));
});

If from different class:

add_action( 'rest_api_init', function () {
register_rest_route( 't2mchat/v2', '/get_curr_user_lang', array(
'methods' => 'GET',
'callback' => array(new className,'get_user_lang')
));
});

If this solution is not working, a bit more details of your problem will help in defining.

Using c++ class method as a function callback

Usual pattern is to pass the instance pointer this into the PVOID pvContext parameter, then use it within the callback to call a member function.

public class Camera
{
// ...
void ThisTransferEndCallback(HANDLE hCamera, DWORD dwFrameNo, DWORD dwWidth, DWORD dwHeight, WORD wColorArray, PBYTE pbyteRaw);
static void __stdcall TransferEndCallback(HANDLE hCamera, DWORD dwFrameNo, DWORD dwWidth, DWORD dwHeight, WORD wColorArray, PBYTE pbyteRaw, PVOID pvContext);
};

Set the callback as

StTrg_SetTransferEndCallback(cameraHandle, TransferEndCallback, this);

Then write the static callback to dispatch it to the member function

void __stdcall Camera::TransferEndCallback(HANDLE hCamera, DWORD dwFrameNo, DWORD dwWidth, DWORD dwHeight, WORD wColorArray, PBYTE pbyteRaw, PVOID pvContext)
{
((Camera *)pvContext)->ThisTransferEndCallback(hCamera, dwFrameNo, dwWidth, dwHeight, wColorArray, pbyteRaw);
}

The above doesn't include error checking etc.

Call class method inside a callback function

You have several options. The three most common ones:

Create a variable to store a copy of this that you can close over

var that = this;
$("#masterSlider").bind("valuesChanging", function(e, data) {
that.setTimeRange(data.values.min, data.values.max);
});

Use function.prototype.bind on your anonymous function to return another function which has a specified value of this:

$("#masterSlider").bind("valuesChanging", (function(e, data) {
this.setTimeRange(data.values.min, data.values.max);
}).bind(this));

Use an ES6 arrow function instead of an anonymous function:

$("#masterSlider").bind("valuesChanging", (e, data) => this.setTimeRange(data.values.min, data.values.max));


Related Topics



Leave a reply



Submit