Search code examples
phpclosuresphpdoc

PHPdoc Exception object in closure function?


How can i get Exception suggestions in $exception variable?

Now I'm using PHPStorm. As i remember in Netbeans there was a function to create proper PHPdoc.

class Controller {

    /**
     * @param          $params
     * @param callable $callback
     * @return array|\Exception
     */
    public final function query(array $params, $callback = null) {

        try {

            /** another dummy code */

        } catch (\Exception $exception) {

            /** Boom! Error! */
            if (is_null($callback)) return $params; else return $callback(null, $exception);

        }
    }
}

class someController extends Controller {

    public function someFunction() {
        $someParams = [];

        $this->query($someParams, function ($response, $exception) {

            if ($exception) return print $exception->/**getMessage(), getCode() etc */;

            /** more dummy code */
            print $this->render("template.twig", $response);
        });
    }
}

enter image description here


Solution

  • Declare the type of the $exception parameter. It solves all your needs:

    function ($response, \Exception $exception = null) { ...
    

    More than that, it prevents the callback working when it is invoked with an invalid type for argument $expection.

    Declaring the default value (null) for $exception is required to allow calling the function with null for $exception; otherwise PHP triggers an error when the function is invoked with null as its second argument.