Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing method as parameter in PHP [duplicate]

I have a class in PHP like this:

class RandomNumberStorer{

     var $integers = [];

     public function store_number($int){
         array_push($this->integers, $int);
     }

     public function run(){
         generate_number('store_number');
     }
}

...elsewhere I have a function that takes a function as a parameter, say:

function generate_number($thingtoDo){ 
     $thingToDo(rand());
}

So I initialise a RandomNumberStorer and run it:

$rns = new RandomNumberStorer();
$rns->run();

And I get an error stating that there has been a 'Call to undefined function store_number'. Now, I understand that that with store_number's being within the RandomNumberStorer class, it is a more a method but is there any way I can pass a class method into the generate_number function?

I have tried moving the store_number function out of the class, but then I then, of course, I get an error relating to the reference to $this out of the context of a class/ instance.

I would like to avoid passing the instance of RandomNumberStorer to the external generate_number function since I use this function elsewhere.

Can this even be done? I was envisaging something like:

 generate_number('$this->store_number')
like image 345
Jon Avatar asked Sep 09 '13 21:09

Jon


1 Answers

You need to describe the RandomNumberStore::store_number method of the current instance as a callable. The manual page says to do that as follows:

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 what you would write is:

generate_number([$this, 'store_number']);

As an aside, you could also do the same in another manner which is worse from a technical perspective, but more intuitive:

generate_number(function($int) { $this->store_number($int); });
like image 100
Jon Avatar answered Oct 19 '22 12:10

Jon