代码之家  ›  专栏  ›  技术社区  ›  Toma Tomov

call\u user\u func\u数组在方法存在时抛出错误

php
  •  1
  • Toma Tomov  · 技术社区  · 7 年前

    这就是我达到目标的方式 _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 方法,该方法位于 :

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

    我做错了什么?非常感谢。

    2 回复  |  直到 7 年前
        1
  •  1
  •   jeroen    7 年前

    $name 它本身不是一个已知的函数;这似乎是世界上的一种方法 CurrencyConverter 班级。

    因此,要调用它,假设它是一个静态方法,您需要如下内容:

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

    请注意,您需要 ... 接线员到 unpack $params

        2
  •  1
  •   Nigel Ren    7 年前

    call_user_func_array($name, $params);
    

    它需要一个名为 $name .

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

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

    如果它不是当前实例中的方法,则替换 $this 以适当的实例。或者将方法更改为 static 替换 美元这个 使用类名。

    推荐文章