Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use private instance methods as callbacks?

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.

like image 575
Allain Lalonde Avatar asked Jun 22 '09 16:06

Allain Lalonde


People also ask

Are instance methods private?

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.

What is callback method?

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.

Why callbacks are needed?

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.

How are callbacks invoked?

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.


1 Answers

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

like image 187
Tom Haigh Avatar answered Sep 24 '22 03:09

Tom Haigh