Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Call to static method from template

Hi all,

as constants are accessible from VOLT by constant() function is there a way to call a static method/property?

Regards



4.7k
Accepted
answer
edited Sep '18

You cannot call functions on objects / access properties that are not a part of or stored in Volt. However, you can extend Volt with your own functions that will call or access something outside Vault and pass result back into you template.

See here http://docs.phalconphp.com/en/latest/reference/volt.html, Extending Volt - Functions.

I'd like to propose a short solution for handling this. First, we need to define a new service.

$di->setShared("static", new \StaticWrapper());`

With the wrapper class looking like this:

Class StaticWrapper 
{
       public function __call($name, $arguments) {
            return call_user_func_array($name, $arguments);
        }

       public function class($className, $methodName, $arguments=array()) {
           return call_user_func_array(array($className, $methodName), $arguments);
       }

 }

In the template, you can now call things like:

static.myGlobalStaticFunction(foo, bar); {# global static #}
static.class("\Some\Namespaced\Class", "classMethod", [foo, bar]); {# class method #}

The DI will automatically place our new service in the template.