Toma Tomov
Toma Tomov

Reputation: 1700

call_user_func_array throws an error when the method exist

This is how I am reaching the _call method:

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

The function throws an error but the method exists below it. My __call looks like:

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');
    }

It passes the if condition but after that the error occures:

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

And this is the convertPriceByGivenCurrencies method which is landed in the below the _call:

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

What am I doing wrong here ? Thank you!

Upvotes: 1

Views: 202

Answers (2)

Nigel Ren
Nigel Ren

Reputation: 57141

Calling it with

call_user_func_array($name, $params);

it is expecting a standalone function called $name.

As it's a method in a class you need to add this information to the callable, if you want to call it on the current instance then use

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

If it isn't a method in the current instance, then replace $this with the appropriate instance. Or change the method to be static and replace $this with the class name.

Upvotes: 1

jeroen
jeroen

Reputation: 91792

$name by itself is not a known function; it seems to be a method in the CurrencyConverter class.

So to call it, assuming it is a static method, you would need something like:

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

Note that you need the ... operator to unpack $params

Upvotes: 1

Related Questions