Pass method as parameter in PHP

I have a class in PHP:

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, for example:

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

So, I initialize RandomNumberStorer and run it:

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

And I get the error "Call undefined function store_number". Now I understand that with the store_number located in the RandomNumberStorer class, this is more of a method, but is there a way to pass the class method to the generate_number function?

I tried to move the store_number function from the class, but then of course I get an error message related to the link to $this from the context of the class / instance.

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

Can this be done? I provided something like:

  generate_number('$this->store_number') 
+7
function php parameters
source share
1 answer

You need to describe the RandomNumberStore::store_number current instance as callable . The manual page says the following:

The object instance method is passed as an array containing the object at index 0 and the method name at index 1.

So what would you write:

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

Aside, you can also do the same thing differently, which is worse from a technical point of view, but more intuitive:

 generate_number(function($int) { $this->store_number($int); }); 
+9
source share

All Articles