PHP

PHP

Made by DeepSource

Nested function declaration is discouraged PHP-W1023

Anti-pattern
Critical

This issue is raised when a function is declared inside another function or method. The nested function is always created in the global scope and not in the enclosing function or method's scope.

This will also lead to a Fatal Error during runtime if the enclosing function or method is called more than once. This happens because the enclosed function is defined in the Global scope when the enclosing function is called the first time. On subsequent calls, PHP will find the enclosed function already defined and run into an error.

It is therefore recommended to refactor it to an anonymous function/closure, class method, or a top-level-defined function.

Bad Practice

class User
{
    public function get()
    {
        // Nested function. Calling `get()` more than once would result in a fatal error.
        function fetchUser()
        {
        }
    }
}

Recommended

Refactor it to use anonymous function/closure:

class User
{
    public function get()
    {
        $closure = function () {
        }
    }
}

Or, refactor it to use a private class method:

class User
{
    public function get()
    {
        $this->fetchUser();
    }

    private function fetchUser()
    {
    }
}