下面的代码是我试图理解的内容的简化示例。
我正在使用一个使用回调来处理多个请求的外部库。 最终,我一直在试图弄清楚如何为每个数组元素进行Test->inc()
调用ExternalLib
,然后等待所有回调执行后再继续。
如您所见,第 18 行的致命错误是由于通过 call_user_func
调用的方法造成的。 我该怎么做,或者有没有更好的方法?
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));
期望输出:
array(3) {
[5]=>
int(6)
[6]=>
int(7)
[9]=>
int(10)
}
此代码也可在代码键盘上找到
问题不是时间/等待问题。这是一个静态与实例化的问题。
使用 call_user_func(array('Test','incCallback')...
调用函数与调用 Test::incCallback
相同。进行静态调用时不能使用 $this
。
您需要修改外部库以使用实例化对象,或者修改 Test 类以使用所有静态数据。
编辑
我不知道你到底想完成什么,但如果让类作为静态类运行是你唯一的选择,那么这就是你必须做的......
您的代码还有其他几个问题:
- 根据您想要的输出,您不需要
a[] = array($in, $out)
而是a[$in] = $out
-
$num++
在调用函数之前不会递增...你想要++$num
这是一个工作示例...
class Test {
public static $a;
public function inc(array $ints){
$request = new ExternalLib();
foreach ($ints as $int) {
$request->incriment($int);
}
while( count(self::$a) < count($ints) ) {}
self::dump();
}
public function incCallback($in, $out) {
/* append data to Test class array */
self::$a[$in] = $out;
}
public function dump() {
/* Print to screen */
var_dump(self::$a);
}
}
class ExternalLib {
/* This library's code should not be altered */
public function incriment($num) {
call_user_func(array('Test','incCallback'), $num, ++$num);
}
}
Test::$a = array();
Test::inc(array(5,6,9));