12

I have checked magento2 ,There are two types of parameters can be send to

around method

  • \Closure $proceed example aroundSave(\Magento\Catalog\Model\Product $subject, \callable $proceed)
  • \callable $proceed example aroundSave(\Magento\Catalog\Model\Product $subject, \Closure $proceed)

Now my question:

  1. What is different between closure and callable?
  2. Why use we define type two different types for $proceed parameter?
  3. What are use of this two types parameters?

Can any describe it details

  • 1
    Nice question! Amit – Rakesh Jesadiya Nov 30 '17 at 10:19
  • could some one explain it again in simple terms? it will be very helpful – aravind Aug 5 '19 at 6:57
9

You have an answer here : https://stackoverflow.com/a/29730810/4629261

The difference is, that a [Closure] must be an anonymous function, where [callable] also can be a normal function.

You can see/test this with the example below and you will see that you will get an error for the first one:

function callFunc1(Closure $closure) {
    $closure();
}

function callFunc2(Callable $callback) {
    $callback();
}

function xy() {
    echo 'Hello, World!';
}

callFunc1("xy"); // Catchable fatal error: Argument 1 passed to callFunc1() must be an instance of Closure, string given
callFunc2("xy"); // Hello, World!

So if you only want to type hint anonymous function use: Closure and if you want also to allow normal functions use callable as type hint.

http://php.net/manual/en/class.closure.php

http://php.net/manual/en/language.types.callable.php

In the Magento doc, they suggest to use [callable]

Before the list of the original method’s arguments, around methods receive a callable that will allow a call to the next method in the chain. When the callable is called, the next plugin or the observed function is called.

When you wrap a method which accepts arguments, your plugin must also accept those arguments and you must forward them when you invoke the proceed callable.

http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html#defining-a-plugin

  • good, so what is best of use in around method to magento? – Amit Bera Nov 30 '17 at 10:42
  • 1
    I edited above, Magento suggest to use [callable] – Vinz Nov 30 '17 at 10:57

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.