My particular scenario involves doing some text transformation using regular expressions within a private method. The private method calls preg_replace_callback, but is seems that callbacks need to be public on objects, so I'm stuck breaking out of the private world and exposing implementation details when I'd rather not.
So, in a nutshell: Can I use an instance method as a callback without losing encapsulation?
Thanks.
As of Java 9, methods in an interface can be private. A private method can be static or an instance method. Since private methods can only be used in the methods of the interface itself, their use is limited to being helper methods for the other methods of the interface.
A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.
Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
Yes, it seems you can:
<?php
//this works
class a {
private function replaceCallback($m) { return 'replaced'; }
public function test() {
$str = " test test ";
$result = preg_replace_callback('/test/', array($this, 'replaceCallback'), $str);
echo $result;
}
}
$a = new a();
$a->test();
//this doesn't work
$result = preg_replace_callback('/test/', array(new a(), 'replaceCallback'), ' test test ');
echo $result;
So it seems that preg_replace_callback()
, or PHP's callback mechanism, is aware of the scope in which it was called.
Tested on 5.2.8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With