0

Original

public function addOrderCommentsTo($order, $prevOrder)
    {
        //something
    }

The original function doesn't return anything. Do I need to add return $result inside Plugin after function, what if I don't return anything?

Plugin

    public function afterAddOrderCommentsTo(RecurringOrder $subject, $result, $order, $originalOrder)
    {
        //something
        return $result;
    }

1 Answer 1

1

As we can see in \Magento\Framework\Interception\Interceptor::___callPlugins:146, return value of after plugin will be used as result for function.

foreach ($currentPluginInfo[DefinitionInterface::LISTENER_AFTER] as $code) {
    $pluginInstance = $pluginList->getPlugin($type, $code);
    $pluginMethod = 'after' . $capMethod;
    $result = $pluginInstance->$pluginMethod($subject, $result, ...array_values($arguments));
}

From PHP documentation https://www.php.net/manual/en/functions.returning-values.php

Note:

If the return is omitted the value null will be returned.

It means that you should just omit return in your plugin in case of origin function return type is void.

You can use return $result, but this code will be incorrect after adding return type declaration to your function.

https://www.php.net/manual/en/migration71.new-features.php

A void return type has been introduced. Functions declared with void as their return type must either omit their return statement altogether, or use an empty return statement. null is not a valid return value for a void function.

public function afterAddOrderCommentsTo(
    RecurringOrder $subject,
    $result,
    $order,
    $originalOrder
): void {
    //something
    return $result; // Fatal error: A void function must not return a value
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.