该方法存在时,call_user_func_array引发错误

时间:2018-11-13 07:38:15

标签: php

这是我达到_call方法的方式:

$model->delivery_price = $currencyConverter->convertPriceByGivenCurrencies(
                        $model->delivery_price,
                        $currency->id,
                        $model->order_currency
                    );

该函数引发错误,但该方法存在于其下方。我的__call如下:

public function __call($name, $params)
    {
        if(method_exists(CurrencyConverter::className(), $name)){
            if($params[0] == 0 || $params[0]){
                call_user_func_array($name, $params);
            }else{
                throw new \Exception('Price must be a valid number!');
            }
        }
        throw new NotFoundException('Function doesn\'t exist');
    }

它通过了if条件,但之后发生了错误:

call_user_func_array() expects parameter 1 to be a valid callback, function 'convertPriceByGivenCurrencies' not found or invalid function name

这是convertPriceByGivenCurrencies方法,它位于_call下面:

protected function convertPriceByGivenCurrencies($product_price, $product_price_currency_id, $select_currency_id)
    {
      ............
    }

我在这里做错了什么?谢谢!

2 个答案:

答案 0 :(得分:1)

$name本身不是已知功能;它似乎是CurrencyConverter类中的一种方法。

要调用它,假设它是一个静态方法,则需要类似以下内容的东西:

CurrencyConverter::$name(...$params);

请注意,您需要...运算符来unpack $params

答案 1 :(得分:1)

通过

调用
call_user_func_array($name, $params);

期望有一个名为$name的独立功能。

由于它是类中的一种方法,因此需要将此信息添加到callable中,如果要在当前实例上调用它,请使用

call_user_func_array(array($this,$name), $params);

如果当前实例中不是方法,则将$this替换为适当的实例。或将方法更改为static并将$this替换为类名。