We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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



5.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 https://docs.phalcon.io/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.