Reputation: 2173
I have an array of stdclass objects. How can I assign it to a smarty template?
I tried to do this:
$smarty->assign( 'objects', $x->getAllObjects() );
but the result is an error:
Catchable fatal error: Object of class Object could not be converted to string
Thanks
edit: I also tried:
$smarty->registerObject( 'objects', $x->getAllObjects() );
and in the template file I did:
{foreach from=$objects item=o}
{$o}
{/foreach}
but I get a notice:
Notice: Undefined index: objects
and I can't access the elements of objects
array.
Upvotes: 0
Views: 3566
Reputation: 111839
We don't know what is your $x
and getAllObjects()
method.
However the following code for assigning objects for Smarty works without a problem
PHP file:
class X
{
private $_objects;
public function __construct()
{
$a = new StdClass();
$a->name = 'John';
$b = new stdClass();
$b->name = 'Tom';
$this->_objects[] = $a;
$this->_objects[] = $b;
}
public function getAllObjects()
{
return $this->_objects;
}
}
$x = new X();
$smarty->assign('objects', $x->getAllObjects());
Smarty file:
{foreach from=$objects item=o}
{$o->name}
{/foreach}
Upvotes: 1
Reputation: 1731
$x->getAllObjects()
is probably returning an object.
you can cast it to a string:
$string = (string) $x->getAllObjects();
Upvotes: 0
Reputation: 914
This depends on your smarty version.
But looking at the error messager you may need to do the following
$smarty->register_object('objects', $x->getAllObjects());
Upvotes: 0