The following code is a simplified example of what I’m trying to understand.
I’m using an external library that uses callbacks to process multiple requests. Ultimately I’ve been trying to figure out how to make Test->inc() call ExternalLib for each array element, then wait for all callbacks to be executed before continuing.
As you can see, the fatal error on line 18 is due to the method being called via call_user_func. How can I do this, or is there perhaps a better method?
class Test {
public $a = array();
public function inc(array $ints){
$request = new ExternalLib();
foreach ($ints as $int) {
$request->increment($int);
}
while( count($this->a) < count($ints) ) {
usleep(500000);
}
$test->dump();
}
public function incCallback($in, $out) {
/* append data to Test class array */
$this->a[] = array($in => out); /* Fatal error: Using $this when not in object context */
}
public function dump() {
/* Print to screen */
var_dump($this->a);
}
}
class ExternalLib {
/* This library's code should not be altered */
public function increment($num) {
call_user_func(array('Test','incCallback'), $num, $num++);
}
}
$test = new Test();
$test->inc(array(5,6,9));
Desired output:
array(3) {
[5]=>
int(6)
[6]=>
int(7)
[9]=>
int(10)
}
This code also available at codepad
The problem isn’t a timing/waiting issue. It’s a static vs. instantiated issue.
Calling the function using
call_user_func(array('Test','incCallback')...is the same as callingTest::incCallback. You can’t use$thiswhen making a static call.You will either need to modify the external lib to use an instantiated object or modify the Test class to use all static data.
Edit
I don’t know exactly what you’re looking to accomplish, but if making the class operate as a static class is your only option, then that’s what you have to do …
There are a couple other issues with your code:
a[] = array($in, $out)but rathera[$in] = $out$num++will not increment until after the function is called … you want++$numHere is a working example …