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.

Volt - $compiler->addFunction ( Custom function with the instance of the ControllerBase.php class )


Hi everyone! This is my first post on the forum.

Could you help me with this question of object-oriented programming in PhalconPHP?


$compiler->addFunction('myfunction',function($resolvedArgs,$exprArgs) use ($compiler){
    $arg = $compiler->expression($exprArgs[0]['expr']);
    return 'ControllerBase::myfunction('.$arg.')';


public static function myfunction($myString){
    if ($this->session->has('mysession')) {
        return $myString;
    } else {
        return 'session not found';


<p>{{ myfunction('myString') }}<p>

Error message I'm getting:

Fatal error: Using $this when not in object context in

Error line: "if ($this->session->has('mysession')) {"

How to use the instance "$this->session" ( or any other method or property instantiated in ControllerBase.php ) in the function "$compiler->addFunction" ( service.php )?


edited Mar '16

You declared myFunction in your controller as static, therefor you are not allowed to use $this inside.

Access DI like so:

public static function myfunction($myString) {
    $di = \Phalcon\DI::getDefault(); 
    if ($di->getSession()->has('mysession')) {

And welcome to the forum friend :)



Hi Nikolay, thanks for answering.

But I would like to use the functions that are in the "ControllerBase.php" class, I wouldn't want to write code within "service.php":

I thought I'd get something like:

 return 'ControllerBase::myfunction('.$arg.')';

How can I use a function within the "ControllerBase.php" class with all the running instance ($this) and then return some value?

Best regards,



Just check my example and modify your code.

PHP does not allow using $this inside static method.



I'm sorry, You're right! Thanks.

Best regards,