使用$ this在Laravel中调用call_user_func_array

时间:2017-01-24 07:38:09

标签: php laravel laravel-4

我有:

$this->addRow('$this->userRepo->dateTargetedActual', [$teamMember, $date->year, $date->month], $year, 'Stage target', 'target', $teamMember->image);

但它给了我错误:

call_user_func_array() expects parameter 1 to be a valid callback, function '$this->userRepo->dateTargetedActual' not found or invalid function name

如何让它发挥作用?

protected function addRow($func, $params, $data, $year, $traderName, $rowName, $type, $image = null) {
    $date = Carbon::createFromDate($year, 4, 1);
    $total = 0;
    $traderName = $traderName.' '.str_replace(' ', '_', strtolower($rowName));
    $params[] = $date->month;
    for ($i = 1; $i < 13; $i++) {
        $result = call_user_func_array($func, $params);
        $data['traders'][$traderName]['amounts'][] = $result;
        $total += $result;
        $date->addMonth();
    }
    $data['traders'][$traderName]['amounts'][] = $total;
    $data['traders'][$traderName]['image'] = $image;
    $data['traders'][$traderName]['row_name'] = $rowName;
    $data['traders'][$traderName]['row_type'] = $type;
    return $data;
}

2 个答案:

答案 0 :(得分:0)

我认为你不应该将$this->userRepo->dateTargetedActual换成字符串。

试试这个: $this->addRow($this->userRepo->dateTargetedActual(), [$teamMember, $date->year, $date->month], $year, 'Stage target', 'target', $teamMember->image);

答案 1 :(得分:0)

由于我们没有addRow的代码,我们必须根据错误消息猜测addRow的第一个参数作为第一个参数传递给{{1}期望第一个参数是回调。

如果call_user_func_array()实际上拥有一个回调函数,那么你只需要在不引用它的情况下传递该值,它将由$this->userRepo->dateTargetedActual函数执行。

call_user_func_array()

如果$this->addRow($this->userRepo->dateTargetedActual, [$teamMember, $date->year, $date->month], $year, 'Stage target', 'target', $teamMember->image); 包含一段数据,并且您需要一个回调函数来返回该数据,那么您可以定义内联函数调用:

$this->userRepo->dateTargetedActual