Search code examples
phpslimslim-3

Slim 3 container undefined method when creating custom container function


I'm trying to create custom functions with parameters within my container but everything I do ends up failing. My current code is as folllows:

$container['myFunction'] = function($container) {
    return function($arg) {
        return $arg;
    };
};

// Called from a route:
echo $this->myFunction("test"); // Call to undefined method Slim\Container::myFunction()

Am I doing something wrong? From what I read online this should be the correct way to define a custom container functions with Slim 3. Any help would be great, thanks!


Solution

  • You need to create an instance of the container service before you can use it.

    $myFunc = $this->myFunction;
    echo $myFunc('test');
    

    Or on one line:

    echo ($this->myFunction)('test');