D
D
Denis Shpuganich2017-02-09 14:11:10
PHP
Denis Shpuganich, 2017-02-09 14:11:10

How to execute a function in a static variable?

I have some View class.
Its instance is created during controller operation.
For example:

$view = new View('index.twig');
$view->render();

Inside the View, a Twig_Environment instance is created, where parameters for the template engine are set.
It also defines things like global variables for all templates and Twig extension functions:
class View
{
    public function __construct($tpl = "")
    {
        $loader = new Twig_Loader_Filesystem(TPL_DIR);
        $this->twig = new Twig_Environment($loader, self::$twigParams);

        // Расширение функционала Twig
        $twig->addFunction(new Twig_SimpleFunction('file_exists', function($filename)
        {
                return file_exists(ROOT.$filename);
        }));

        // Здесь ещё много таких функций и фильтров

        if($tpl) 
            $this->setTpl($tpl);
    }
    ...
}

With this design, it becomes necessary to constantly edit the View class in order to change the set of filters / functions, and this is not entirely correct.
I want to take these actions to some init system controller, where to set all these settings, and then receive them in the View class during initialization.
I tried by analogy with JS:
// controllers/init.php
View::$extFunc = function(Twig_Environment &$twig)
{
    $twig->addFunction(new Twig_SimpleFunction('file_exists', function($filename)
    {
        return file_exists(ROOT.$filename);
    }));
}

// View.class.php
class View
{
    public static $extFunc;

    public function __construct($tpl = "")
    {
        ...
        if(is_callable(self::$extFunc)) // Вот эта проверка проходит, значит там-таки функция
            self::$extFunc($this->twig); // Вот тут ошибка "Function name must be a string"
        ...
    }
}

Maybe there is another way to execute the function that is in the $extFunc variable?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Shpuganich, 2017-02-09
@dyonis

The issue was resolved by creating an extension of the Twig_Extension class in which you can override / add everything you need.
twig.sensiolabs.org/doc/2.x/advanced.html#creating...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question