12

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')
4

1 回答 1

15

您需要将RandomNumberStore::store_number当前实例的方法描述为可调用的。手册页说这样做如下:

实例化对象的方法作为数组传递,该数组包含索引 0 处的对象和索引 1 处的方法名称。

所以你要写的是:

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

顺便说一句,你也可以用另一种方式来做同样的事情,这从技术角度来看更糟糕,但更直观:

generate_number(function($int) { $this->store_number($int); });
于 2013-09-09T21:52:54.157 回答