静的関数を呼び出す方法や、twigで静的変数を使用する方法はありますか?
静的ヘルパー関数のクラスがあり、テンプレートで1つまたは2つ使用したいと思います。
私がそれをやってしまったいくつかの方法。
1 つ目は、静的関数を呼び出すことができる関数です。
$twig = new Twig_Environment($loader);
$twig->addFunction('staticCall', new Twig_Function_Function('staticCall'));
function staticCall($class, $function, $args = array())
{
if (class_exists($class) && method_exists($class, $function))
return call_user_func_array(array($class, $function), $args);
return null;
}
その後、次のように使用できます。
{{ staticCall('myClass', 'mymethod', [optional params]) }}
もう一つは、魔法の方法を使うことです。
クラスを render $context に追加します
$data['TwigRef'] = new TheClass();
class TheClass
{
public function __call($name, $arguments) {
return call_user_func_array(array('TheClass', $name), $arguments);
}
...
}
その後、次のように使用できます。
{{ TwigRef.myMethod(optional params) }}
承認された関数のみが呼び出されるように、追加のチェックを追加するのがおそらく最善です。