In some scenarios, you may need to pass class methods as callbacks to other functions for efficient execution of specific tasks. This article guides you through the various mechanisms for achieving this.
To pass a function as a callback, you can directly provide its name as a string. However, this method is not applicable to class methods.
Class instance methods can be passed as callbacks using an array with the object as the first element and the method name as the second. This approach works both within and outside the same class.
// Inside the same class
$this->processSomething([$this, 'myCallback']);
$this->processSomething([$this, 'myStaticCallback']);
// Outside the same class
$myObject->processSomething([new MyClass(), 'myCallback']);
$myObject->processSomething([new MyClass(), 'myStaticCallback']);
Static class methods do not require an object instance. They can be passed directly as an array containing the class name and the method name.
// Inside the same class
$this->processSomething([__CLASS__, 'myStaticCallback']);
// 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 the mentioned methods, you can also pass anonymous functions as callbacks, but this may require modifications to your code structure.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3