1
class MyClass {
    public $myMember = ['key1' => 'val1', 'key2' => 'key2'];
}

$smarty = new Smarty();
$smarty->assign('object', new MyClass());
$smarty->assign('member', 'myMember');
$smarty->assign('key', 'key1');

How can I access $object->$member.$key in my Smarty template without introducing a new variable?

Straight forward {$object->$member.$key} results in an error (I guess . has higher precedence than ->?)

I would like something that doesn't involve introducing a new variable, hence not the obvious {$temp=$object->$member}{$temp.$key}

2
  • does {{$object->$member}.$key} work? Commented Jul 23, 2014 at 14:53
  • No, Smarty gives syntax error on the . Commented Jul 23, 2014 at 14:55

1 Answer 1

1

I'm afraid there is no standard method to do that.

When you use:

{$object->$member|var_dump}

Smarty knows that it's an array and shows it values but I don't know any method to access element of this array.

However what you can do is to create Smarty modifier:

// modifier.get.php
function smarty_modifier_get($array, $index)
{
    return $array[$index];
}

register your plugin dir:

$smarty->addPluginsDir('myplugins');

and then you can use syntax:

{$object->$member|get:$key} 

Of course you can change get to something shorter if you will use it often if you need.

But there is also other thing I should mention in reply. I've never used such assignment to use properties of object as variables or keys as variables.

In this case also you can simple assign to Smarty array:

$obj = new MyClass();
$smarty->assign('array',$obj->myMember);

and then in Smarty you could manipulate standard array without complex syntax or modifiers. So maybe you should consider it but of course it's up to you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.