Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smarty call a static class method

Tags:

php

smarty

I want to call a php method in my smarty template.

I have the class

class TestClass
{
    public static myMth($vars) {
        var_dump($vars);
    }
}

In my template i put:

{TestClass::myMth($someVar)}

That doesn't work. I have the error:

Parse error: syntax error, unexpected 'myMth' (T_STRING), expecting variable (T_VARIABLE)

Is there something wrong in my code ?

like image 699
Sancho Avatar asked Aug 08 '26 01:08

Sancho


1 Answers

In fact it works without a problem (Smarty 3.1.19):

In PHP:

$data['elements'] = [1,2,3,4,5,6,7,8,9,10,11];
$smarty->assign('someVar',$data);

class TestClass
{
    public static function myMth($vars) { // added function word here - you missed it in question
        var_dump($vars);

        echo "<br />test test test<br />";
    }
}

In Smarty:

{TestClass::myMth($someVar)}

Output:

array(1) { ["elements"]=> array(11) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) [5]=> int(6) [6]=> int(7) [7]=> int(8) [8]=> int(9) [9]=> int(10) [10]=> int(11) } }
test test test

However I don't think it's the best way of using Smarty.

You should rather use:

$smarty->assign('result', TestClass::myMth($data));

Why? It's quite simple. Smarty is Template engine and you should only display data here. You should not launch classes/method and so on. What if myMyth function name will change or arguments will change? You will need to change your Smarty template files. Better is to assign to Smarty only output of this method.

However if you still want to do that you can also look at Static classes section at Smarty website.

like image 62
Marcin Nabiałek Avatar answered Aug 10 '26 15:08

Marcin Nabiałek